views:

134

answers:

2

I have a JFrame on which I am using overriding the paint method to display some graphics. I also want to add a JPanel to it that will show up on top of the graphics. Right now, all I see is the graphics created from JFrame paint method.

Here's my JPanel:

public class NoteDraw extends JPanel {

    public NoteDraw() {
        setSize(200, 100);
        setBackground(Color.BLACK);
    }

    @Override public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.red);
        g.fillRect(0, 0, 100, 100);
    }
}

Here's my JFrame:

public class ui extends JFrame {
    public void paint(Graphics g) {
        //do some drawing here...
    }
}

Here's my main:

public class Main {
    static ui main_gui = new ui();

    public static void main(String[] args) {
        NoteDraw note = new NoteDraw();
        main_gui.getContentPane().add(note);
        main_gui.setVisible(true);
    }
}
A: 

Remember to call super.paint() when you override your paint() method.

This way, you still use the behavior defined in the parent class, and you can add your modifications safely.


Resources :

Colin Hebert
Thanks, mentioned in a comment earlier, but that's not the problem.
tybro0103
+1  A: 

You should NEVER override the paint() method of a JFrame (unless you really know what you are doing). This method is responsible for all the optimized painting behaviour of Swing.

Custom painting should always be done by overriding the paintComponent() method of a Swing component like you have done on your NoteDraw panel.

The reason the code in the paint method doesn't show is because the NoteDraw panel is opaque and therefore the panel paints over top of the Graphics code in your paint method.

So the solution is to move the Graphics painting code to the NoteDraw panel.

Or if you are trying to create some kind of background image for your frame then you can try using the Background Panel.

Or if you truly do need custom painting then you create a background panel and override the paintComponent() method. Then you set the layout to a BorderLayout and add this panel to the frame. Then you make your NoteDraw panel non-opaque and add it to the custom background panel. Now the background will show through on the NoteDraw panel.

camickr