JeffBr
JeffBr

Reputation: 25

Adding a Oval to a JPanel (paintComponent)

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!

Upvotes: 0

Views: 10185

Answers (2)

JLeNoir
JLeNoir

Reputation: 39

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.

Upvotes: 2

Cameron Skinner
Cameron Skinner

Reputation: 54276

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

Upvotes: 4

Related Questions