Question

In a layout with nested JPanel i wish to add a drawn oval.

For this i use the following:

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);

    g.setColor(Color.GRAY);
    g.fillOval(20, 20, 20, 20);
}

Now in one of my panels i wish to add this oval, but i cannot seem to add this.

JPanel myPanel = new JPanel();
myPanel.setLayout(new GridLayout(0, 2));
//myPanel.add(...); here i wish to add the drawn oval

Any input appreciated!

Was it helpful?

Solution

The way to do this is to have a subclass of JComponent that does the drawing you want, then add that to your layout.

class OvalComponent extends JComponent {
    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.GRAY);
        g.fillOval(20, 20, 20, 20);
    }
}

In your GUI construction code you can have this:

JPanel panel = new JPanel(new GridLayout(0, 2));
panel.add(new OvalComponent());

OTHER TIPS

You use mypanel.add(...) for other GUI elements. The oval you want to draw will be a java2d object, which you will have to paint on to the panel. For that you have to override the panel's paint() method with the code you posted above.

 JPanel panel = new JPanel() {
    @Override
    public void paint(Graphics g) {
        g.drawRect(100, 100, 100, 100);
    }
 };

You override the native method in the JPanel class that allows users to add paint components to it. With this, you can add all of your normal graphics input and it will show up. That line of code should produce a square at coordinate (100, 100) relative to the top left corner of the panel.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top