Java 如何添加一个将JPanel扩展到JFrame的类?
对于我的任务,我得到了以下代码:Java 如何添加一个将JPanel扩展到JFrame的类?,java,swing,layout,jframe,jpanel,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 L
// 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
}
}
}
如果我明白你的要求。。。在作业中,您被要求根据自己的需要扩展JPanel。请注意,如果没有扩展JPanel,您将如何添加它:
JFrame myFrame = new JFrame();
JPanel myPanel = new JPanel();
myFrame.add(myPanel);
myFrame.pack();
myFrame.setVisible(true);
这会将JPanel添加到JFrame中,并将其设置为可见。由于myFrame类扩展了JPanel,您应该能够通过创建panel类的新实例并将其添加到JFrame中来完成类似的工作
您不希望在paintComponent()
中执行此部分,因为paintComponent()
可能会被多次调用。查看paintComponent()
的功能。@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);
您必须具有以前使用
JPanel
作为主容器的代码列表。您的教授建议您应该使用清单(8.5和8.6),并尝试使用MyPanel
而不是headpaintcomponent受保护不公开这可能会引起您的兴趣:-)创建框架或面板的新实例不应该在paintComponent()方法中进行,也不应该从paintComponent()方法调用!这两个发布的代码都不会编译,因为图像未声明。是的。作为一些一般性建议,在设置框架可见之前,在框架上完成所有工作是一种很好的做法,而且您可能还希望将其移动到其他位置。。。类似于main函数或从main调用的方法。可能还想给您的面板命名一些不同的名称,如果只是为了不让自己感到困惑的话。如果您能检查我的更新代码,我回答了自己的问题(我不知道如何在注释中添加代码文本)。我必须使用我的教授给我的代码,否则我会被扣分。对于这样的问题,我建议用新代码更新你的问题,因为评论是发布新代码的糟糕格式。无论如何,你教授的初始代码在我看来很好,只是确保你没有试图在自定义面板类中设置框架。