如何添加一个将JPanel扩展到JFrame的类?

时间:2012-10-16 05:59:35

标签: java swing layout jframe jpanel

对于我的任务,我得到了这段代码:

// 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
    }
 }
}

我的教授还说:您还需要查找如何创建并向JPanel添加JFrame。如果您可以创建并添加JPanel,那么您需要做的就是替换' MyPanel'对于班级名称' JPanel'此代码将在窗口框架上显示图像。

他的意思是" 然后您需要做的就是替换' MyPanel'对于班级名称' JPanel'并且此代码将在窗口框架上显示图像"?我对我应该替换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
    }
 }
}

2 个答案:

答案 0 :(得分:5)

如果我理解你的要求是正确的......在你的任务中,你被要求根据自己的需要扩展JPanel。请注意如果JPanel未被扩展,您将如何添加它:

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

这会将JPanel添加到JFrame packs并将其设置为可见。由于myFrame类扩展了JPanel,因此您应该可以通过创建面板类的新实例并将其添加到JFrame来执行非常类似的操作。

您不希望在paintComponent()中执行此部分,因为paintComponent()可能会被多次调用。点击here查看paintComponent()的内容。

答案 1 :(得分:3)

@Hyper Anthony

所以它会与此类似吗?:

MyPanel Mypanel= new MyPanel();
JFrame Myframe= new JFrame();
Myframe.setSize(500,400);
Myframe.add(Mypanel);
Myframe.setVisible(true);
Myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);