1suming
1suming

Reputation: 11

Java Swing paint() not working

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

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. However, when I change the size of jframe, it is displayed.

What is wrong with the code snippets?

Upvotes: 0

Views: 137

Answers (1)

Reimeus
Reimeus

Reputation: 159854

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.

Upvotes: 4

Related Questions