0

我写了一个简单的 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 的大小时,它会显示出来。

代码片段有什么问题?

4

1 回答 1

4

The problem is that the painting done for JButton 'paints over' the custom painting that you have already done in your paint() method.

I would create another custom JComponent sub class and place this paint functionality there. Also better to use paintComponent.

于 2012-10-06T12:44:55.407 回答