Search code examples
javaswingjpanelpaintcomponent

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!


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