开发者

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 EllipseComp开发者_如何学Conent();
       frame.add(component);

       frame.setVisible(true);
   }
}


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.


Do not resize components within paintComponent. In fact, do not create objects or do any program logic within this method. The method needs to be lean, fast as possible, do drawing, and that's it. You must understand that you do not have complete control over when or even if this method is called, and you certainly don't want to add code to it unnecessarily that may slow it down.

You should create your ellipse in the class's constructor. To resize it according to the JComponent's size and on change of size, use a ComponentListener.:

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 {
    Ellipse2D ellipse = null;

    public EllipseComponent {
        ellipse = new Ellipse2D.Double(0,0,150,200);
        addComponentListener(new ComponentAdapter() {
           public void componentResized(ComponentEvent e) {
              // set the size of your ellipse here 
              // based on the component's width and height 
           }
        });
    }

    public void paintComponent(Graphics g)
    {
        Graphics2D g2 = (Graphics2D) g;
        g2.draw(ellipse);
        g2.setColor(Color.red);
        g2.fill(ellipse);
    }
}

Caveat: code not run nor tested

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜