gpt4 book ai didi

java - 相对于面板java绘制椭圆

转载 作者:行者123 更新时间:2023-12-01 18:33:29 26 4
gpt4 key购买 nike

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

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

其中wh是面板的尺寸。因此,通过这样做,当面板改变其大小时,椭圆将自动调整大小。

我已经尝试过这个,但实际上它不起作用,我编写此代码仅用于测试。

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

最佳答案

感谢您的代码片段。为了使其工作,您需要在 Help_Option-Constructor 中初始化椭圆,否则它将在 0, 0 处绘制,宽度和高度分别为 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

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

关于java - 相对于面板java绘制椭圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23092029/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com