我写了一个简单的Swing Frame:
public class super_paint extends JFrame{
private JButton jt;
public super_paint()
{
jt=new JButton("Hello");
jt.setSize(20,10);
Container container=getContentPane();
this.add(jt);
}
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.setColor(Color.red);
g.draw3DRect(10,10,100,100,true);
g.setColor(Color.green);
g.fillOval(50,10,60,60);
g.drawString("A myFrame object", 10, 50 );
}
以下是测试类:
public class super_paint_Test {
public static void main(String[] args)
{
JFrame t=new super_paint();
t.setSize(300,300);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
t.setVisible(true);
}
}
当显示Jframe时,paint()的作用(例如drawRect())不会显示。但是,当我更改jframe的大小时,会显示它。
代码段有什么问题?
答案 0 :(得分:4)
问题在于,为JButton
'绘制的绘画描绘了您在paint()
方法中已经完成的自定义绘画。
我会创建另一个自定义JComponent
子类并将此绘制功能放在那里。使用paintComponent
也更好。