Search code examples
javaswingjframejcomponent

How can I resize and paintComponent inside a frame


Write a program that fills the window with a larrge ellipse. The ellipse shoud touch the window boundaries, even if the window is resized.

I have the following code:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import javax.swing.JComponent;

public class EllipseComponent extends JComponent {
    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;

        Ellipse2D.Double ellipse = new Ellipse2D.Double(0,0,150,200);
        g2.draw(ellipse);
        g2.setColor(Color.red);
        g2.fill(ellipse);
    }
}

And the main class:

import javax.swing.JFrame;

public class EllipseViewer {
   public static void main(String[] args)
   {
       JFrame frame = new JFrame();
       frame.setSize(150, 200);
       frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

       EllipseComponent component = new EllipseComponent();
       frame.add(component);

       frame.setVisible(true);
   }
}

Solution

  • in your EllipseComponent you do:

    Ellipse2D.Double ellipse = new Ellipse2D.Double(0,0,getWidth(),getHeight());

    I'd also recommend the changes given by Hovercraft Full Of Eels. In this simple case it might not be an issue but as the paintComponent method grows in complexity you realy want as little as possible to be computed in the paintComponent method.