PaintComponent不叫netbeans GUI
问题描述:
我对netbean的图形系统是全新的,并且一直在用java教科书挣扎。我试图制作一个简单的程序来展示一些东西,并且完全按照它想要的方式来跟踪这本书。我在我的研究中发现了一些其他有类似问题的人。这些人倾向于被要求使用维度和preferredSize方法,尽管这些都没有在我尝试在java中重现的书中提到。以下是我的代码:PaintComponent不叫netbeans GUI
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
JFrame frame = new JFrame(); //create frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //makes x button end program
frame.setSize(300,200); //determine the size of the frame
ImageIcon image = new ImageIcon("panda.jpg");
ColorPanel p = new ColorPanel(Color.pink, image);
Container pane = frame.getContentPane();
pane.add(p);
frame.setVisible(true); //make frame show up
}
}
public class ColorPanel extends JPanel {
ImageIcon image;
public ColorPanel(Color c, ImageIcon i){
setBackground(c);
image = i;
}
@Override
public void paintComponents(Graphics g){
super.paintComponents(g);
setPreferredSize(new Dimension(100,100));
System.out.println("Blah!");
g.setColor(Color.blue);
g.drawRect(10,25,40,30);
}
}
答
我想你的代码中有一个小的错字。您绝对的意思是覆盖paintComponent()
而不是paintComponents()
。第一个被称为绘制组件,第二个绘制面板中包含的所有组件。既然没有,它就不会被调用。
答
这些人往往会被告知使用的尺寸和首选大小方法
你真的不应该使用了setPreferredSize()。相反,您应该重写getPreferredSize()方法以返回适当的值。另外,您不应该在paintComponent()方法中调用setPreferredSize(),也不要在paintComponent()方法中更改该类的任何属性。
谢谢谢谢谢谢。一切都很完美:) – Anonymous 2011-06-03 16:50:26