ste*_*out 2 java layout swing jpanel jframe
对于我的任务,我得到了这段代码:
// 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
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的教授还说:你还需要查找如何创建和添加JPanel一个JFrame.如果你可以创建AND添加一个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
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我理解你的要求是正确的......在你的任务中,你被要求根据自己的需要扩展JPanel.请注意如果没有扩展JPanel,您将如何添加它:
JFrame myFrame = new JFrame();
JPanel myPanel = new JPanel();
myFrame.add(myPanel);
myFrame.pack();
myFrame.setVisible(true);
Run Code Online (Sandbox Code Playgroud)
这会将JPanel添加到JFrame,将其打包并将其设置为可见.由于myFrame类扩展了JPanel,因此您应该可以通过创建面板类的新实例并将其添加到JFrame来执行非常类似的操作.
您不希望这样做paintComponent(),因为paintComponent()可能会多次调用.点击这里查看是什么paintComponent().