相对于面板java绘制椭圆

时间:2014-04-15 18:52:36

标签: java swing graphics java-2d ellipse

基本上我想在Java中绘制一个椭圆,其大小相对于 JPanel

例如:Ellipse2D e = new Ellipse2D.Double(0, 0, w, h)

w h 是面板的大小。因此,当面板更改其大小时,椭圆将自动调整大小。

我试过这个,但实际上它没有用,我写这段代码只是为了测试。

public class Help extends JFrame{

    public static void main(String [] agrs){
        Help h = new Help();
        h.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        h.init();
    }

    public void init(){
        this.setLayout(new FlowLayout());
        this.setSize(2000, 1000);

        JPanel a = new JPanel();
        a.setPreferredSize(new Dimension(1000, 500));
        a.setBorder(BorderFactory.createLineBorder(Color.yellow, 3));
        Help_Option k = new Help_Option(a.getPreferredSize().width/2, a.getPreferredSize().height/4);
        k.setPreferredSize(new Dimension(1000, 400));
        a.add(k);

        this.add(a);
        this.validate();
        this.setVisible(true);
    }
}

class Help_Option extends JComponent implements MouseMotionListener{
    private static int x, y;
    private Ellipse2D ellipse = new Ellipse2D.Double(0, 0, x, y);
    private Color c = Color.MAGENTA;    

    public Help_Option(int x, int y){
        Help_Option.x = x;
        Help_Option.y = y;
        this.addMouseMotionListener(this);
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D) g;

        g2d.setColor(Color.BLUE);
        g2d.draw(ellipse);

        g2d.setColor(c);
        g2d.fill(ellipse);        

        g2d.setColor(Color.BLACK);
        g2d.setFont(new Font("TimesRoman", Font.BOLD, 20));
        g2d.drawString("Here I am", 250, 100);
    }

    public void setColor(Color c){
        this.c = c;
    }

    @Override
    public void mouseDragged(MouseEvent e) {

    }

    @Override
    public void mouseMoved(MouseEvent e) {
        if(ellipse.contains(e.getX(), e.getY())){
            setColor(Color.GREEN);
            repaint();
        }else{
            setColor(Color.MAGENTA);
            repaint();
        }
    }
}

2 个答案:

答案 0 :(得分:2)

感谢您提供的代码段。为了使其工作,你需要在Help_Option-Constructor中初始化椭圆,否则它在0,0处绘制,widht和高度为0和0。

...
private Ellipse2D ellipse = null; //also works w/o this assignment.
private Color c = Color.MAGENTA;    

public Help_Option(int x, int y){
    Help_Option.x = x;
    Help_Option.y = y;
    ellipse = new Ellipse2D.Double(0, 0, x, y);
    this.addMouseMotionListener(this);
}
...

如果我相应地更改了代码,即使我调整窗口大小,椭圆也会保持其大小。

Image with unscaled ellipse

请给我一个提示(截图)你的意思。

答案 1 :(得分:2)

  

我想绘制一个椭圆,其大小与Java中的JPanel相关。

然后你需要在paintComponent()方法中创建Ellipse对象。您可以使用getWidth()getHeight()方法获取面板的当前大小。