5

I'm trying to create a program that draws shapes (a rectangle on the example below) using JPanel's paintComponent(), but I can't get it to work and can't spot what is wrong.

The code is as follows:

import javax.swing.*;
import java.awt.*;

public class RandomRec{
    JFrame frame;

    public void go(){
        frame = new JFrame();
        frame.setSize(500,500);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        DrawPanel panel = new DrawPanel();
    }

    public static void main (String[] args){
        class DrawPanel extends JPanel{
           public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.setColor(Color.orange);
              g.drawRect(20, 20, 100, 60);
           }
        }

        RandomRec test = new RandomRec();
        test.go();
    }
}

Any help on this would be much appreciated.

Thank you.

*UPDATE* Problem solved! Moving the go() method out of the main method, adding a frame.add(panel) and moving the frame.setVisible(true) to the bottom of the go() method (more specifically, move it after the panel is added to the frame) has sorted the issue. Thank you.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
priboyd
  • 1,917
  • 2
  • 12
  • 19
  • 3
    It's not necessary to update your question with the answer. The best way to indicate "Solved" is to check the checkmark next to the most useful answer. You can also up-vote any answers which helped you. – KatieK Nov 15 '12 at 19:29

2 Answers2

4

Your class DrawPanel is confined to the scope of your main method and is not visible to your constructor.

You need to move DrawPanel out of your main method, then add it to your JFrame:

frame.add(panel);

Also, better to call frame.setVisible(true) after all components have been added.

Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 1
    Spot on - after adding frame.add(panel) the rectangle wouldn't show up. What did the trick really was the frame.setVisible(true) tip. All working now. Class now removed from main method as well (this was something I mistakenly overlooked). Many thanks! – priboyd Nov 15 '12 at 19:18
2

you're never actually adding the panel to the frame, so it is never visible. you need something like

frame.getContentPane().add( panel );

why are you defining the drawpanel class inside the main method? that's rather odd.

John Gardner
  • 24,225
  • 5
  • 58
  • 76
  • that is rather odd and it was something I mistakenly overlooked - fixed now. I tried adding frame.getContentPane().add(panel) and it works as well as frame.add(panel). Thanks! – priboyd Nov 15 '12 at 19:17
  • I believe if you look at the source in jframe, add calls getcontentpane.add anyway. I think the add method on jframe is there for compatibility with awt frame? (and don't forget to mark an answer as correct!) – John Gardner Nov 21 '12 at 19:02