gpt4 book ai didi

java - 如何在按钮单击时添加形状?

转载 作者:行者123 更新时间:2023-12-01 11:06:21 27 4
gpt4 key购买 nike

我有以下代码,我试图在单击按钮时向框架添加一个圆圈,我尝试从我的主函数中调用圆圈类,但不知道如何在之后添加圆圈。请帮助我!

public static void main(String[] args) {
// Create a frame and put a scribble pane in it
JFrame frame = new JFrame("FrameFormula");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
final FrameFormula scribblePane = new FrameFormula();
JPanel shapePanel = new JPanel();
JButton horGap = new JButton("Add a circle");
horGap.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
int[] circleValues = generateRandomValues(300, 300, 50, 150);
int x = circleValues[0];
int y = circleValues[1];
int width = circleValues[2];
int height = width;
Circle circle = new Circle(x, y, width, height);
//scribblePane.addCircle(circle);
}
});
shapePanel.add(horGap);
frame.add(shapePanel, BorderLayout.SOUTH);
frame.getContentPane().add(scribblePane, BorderLayout.CENTER);
}

我创建了单独的类来创建带有 x 和 y 点的圆。

private static int[] generateRandomValues(int maxX, int maxY, 
int minSize, int maxSize) {
Random random = new Random();
int[] values = new int[3];
values[0] = random.nextInt(maxX);
values[1] = random.nextInt(maxY);
values[2] = Math.min(random.nextInt(maxSize) + minSize, maxSize);
return values;
}

static class Circle {

int x, y, width, height;

public Circle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}

public void draw(Graphics g) {
g.drawOval(x, y, width, height);
}
}

最佳答案

it remains for a second and gets removed if something else we do on the panel

查看Custom Painting Approaches自定义绘画的两种常见方法:

  1. 将对象添加到 ArrayList,然后绘制列表中的所有对象
  2. 将对象绘制到 BufferedImage,然后绘制 BufferedImage

演示代码展示了如何使用鼠标随机添加矩形。您的代码显然会略有不同,因为您将使用按钮添加矩形。

因此,从工作代码开始,让它与按钮一起工作。然后更改代码以适用于圆形而不是矩形。

关于java - 如何在按钮单击时添加形状?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32906997/

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