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

How to add a shape on button click?

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

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

我已经创建了单独的 classes 来创建带有 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);
        }
    }

您所做的是创建一个圆圈,而不是调用 draw-方法。你会使用类似的东西:

Circle circle = new Circle(x, y, width, height);
Graphics g = shapepanel.getGraphics();
circle.draw(g);

但这会导致问题,所以我建议您看一下这个帖子:Drawing an object using getGraphics() without extending JFrame

JPanel.

中解释了为什么以及如何始终如一地绘制某些东西

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

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

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

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

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