2

私の課題では、次のコードが与えられます。

// This class/method uses a  global variable that MUST be set before calling/using
// note: You can not call the paint routine directly, it is called when frame/window is shown
// look up the repaint() routine in the book
// Review Listings 8.5 and 8.6
//
public static class MyPanel extends JPanel {
 public void paintComponent (Graphics g) {
    int xpos,ypos;
    super.paintComponent(g);
    // set the xpos and ypos before you display the image
    xpos = 10; // you pick the position
    ypos = 10; // you pick the position
    if (theimage != null) {
        g.drawImage(theimage,xpos,ypos,this);
        // note: theimage global variable must be set BEFORE paint is called
    }
 }
}

私の教授はまた、次のように述べてJPanelJFrameます。を作成して追加できる場合は、クラス名 ' ' をJPanel' ' に置き換えるだけで、このコードによってウィンドウ フレームに画像が表示されます。MyPanelJPanel

「では、クラス名「JPanel」を「MyPanel」に置き換えるだけで、このコードはウィンドウ フレームに画像を表示します」とはどういう意味ですか? をどこに代入するか迷っていMyPanelます。これが私のコードです:

public static class MyPanel extends JPanel {
 public void paintComponent (Graphics g) {
    int xpos,ypos;
    super.paintComponent(g);
    JPanel panel= new JPanel();
    JFrame frame= new JFrame();
    frame.setSize(500,400);
    frame.add(panel);
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // set the xpos and ypos before you display the image
    xpos = 600; // you pick the position
    ypos = 600; // you pick the position
    if (theimage != null) {
        g.drawImage(theimage,xpos,ypos,this);
        // note: theimage global variable must be set BEFORE paint is called
    }
 }
}
4

2 に答える 2

5

あなたが何を求めているのか理解できれば... あなたの任務では、あなた自身のニーズに合わせて JPanel を拡張するよう求められています。拡張されていない場合に JPanel を追加する方法に注意してください。

JFrame myFrame = new JFrame();
JPanel myPanel = new JPanel();
myFrame.add(myPanel);
myFrame.pack();
myFrame.setVisible(true);

これにより、JPanel が JFrame に追加され、パックされ、表示されるように設定されます。myFrame クラスは JPanel を拡張するため、パネル クラスの新しいインスタンスを作成し、それを JFrame に追加することで、非常によく似たことができるはずです。

複数回呼び出される可能性があるためpaintComponent()、この部分を で実行することは望ましくありません。ここpaintComponent()をチェックして、何が機能するかを確認してください。paintComponent()

于 2012-10-16T06:05:28.003 に答える
3

@ハイパーアンソニー

それで、これに似たものになるでしょうか?:

MyPanel Mypanel= new MyPanel();
JFrame Myframe= new JFrame();
Myframe.setSize(500,400);
Myframe.add(Mypanel);
Myframe.setVisible(true);
Myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
于 2012-10-16T06:12:20.887 に答える