Java Swing 绘画()不起作用 [英] Java Swing paint() not working

查看:49
本文介绍了Java Swing 绘画()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个简单的 Swing Frame:

I wrote a simple 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 的大小时,它会显示.

When the Jframe is displayed, what the paint() does (such as drawRect()) does not show. However, when I change the size of jframe, it is displayed.

代码片段有什么问题?

推荐答案

问题在于为 JButton 完成的绘画覆盖"了您在 中已经完成的自定义绘画Paint() 方法.

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

我将创建另一个自定义 JComponent 子类并将此绘制功能放在那里.最好使用 paintComponent.

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

这篇关于Java Swing 绘画()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆