1

I have created a testing version to simplify the problem that I'm having for you guys:

import java.awt.Graphics;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Test extends JFrame {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    JLabel l = new JLabel("hello");
    JPanel cp;

    public Test(){
        setContentPane(cp = new JPanel());
        cp.add(l);
        setSize(200, 200);
        setVisible(true);
    }

    public void paint(Graphics g){
        //do absolutely nothing
    }
}

When you start up the program, you get to see a perfectly blank window. However, if you remove the paint method, the JLabel shows up! (I've had to search for this bug for ages, really). Now, how can I enable a window to both use graphics and regularly draw components? Thanks in advance

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138

1 Answers1

7

1) You should not override paint(..) of JFrame, unless you have a specific purpose for that.

The correct method of drawing in Swing is to:

  • Add a JPanel to JFrame
  • in JPanel, override paintComponent(..) and getPreferredSize() to return correct Dimensions which fit our drawing. NB dont forget to call super.paintComponent(g) as first call in overridden paintComponent method as to honor the paint chain

See this answer of mine which has a few examples for you.

  • Also do not extend JFrame unnecessarilly.
  • Dont call setSize on JFrame rather use a correct LayoutManager and/or override getPreferredSize() - usually done on a JPanel when we are drawing directly or the JPanel will have no size if no components are added, if they are it will only be as big as it needs to fit the components and not the image.
  • and than call pack() on JFrame before setting it visible.

And just incase have a look Concurrency in Swing especially Event-Dispatch-Thread

Community
  • 1
  • 1
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138