对于我的任务,我得到了这段代码:
// 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
}
}
}
我的教授还说:您还需要查看如何创建并将 a 添加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
}
}
}