简体   繁体   English

Java Swing paint()无法正常工作

[英]Java Swing paint() not working

I wrote a simple Swing Frame: 我写了一个简单的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 );
}

The following is the test class: 以下是测试类:

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);
}    

} }

When the Jframe is displayed, what the paint() does (such as drawRect()) does not show. 显示Jframe时,paint()所做的操作(例如drawRect())不会显示。 However, when I change the size of jframe, it is displayed. 但是,当我更改jframe的大小时,将显示它。

What is wrong with the code snippets? 代码段有什么问题?

The problem is that the painting done for JButton 'paints over' the custom painting that you have already done in your paint() method. 问题在于,为JButton完成的绘制会“覆盖”您在paint()方法中已经完成的自定义绘制。

I would create another custom JComponent sub class and place this paint functionality there. 我将创建另一个自定义JComponent子类,并将此绘画功能放置在那里。 Also better to use paintComponent . 也最好使用paintComponent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM