首页 > 解决方案 > 使用 JButton 将形状添加到 JPanel

问题描述

我正在制作一个需要在用户与之交互时添加彩色方块的 JPanel。

public class Corkboard extends JPanel {

    Color colour = Color.RED;
    Graphics gr;
    int x = 20;
    int y = 20;

    public Corkboard() {
        setBorder(new LineBorder(new Color(153, 51, 0), 5));
        setBounds(0, 0, 470, 361);
        setBackground(new Color(225, 200, 150));
    }
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(colour);
        g.fillRect(x, y, 70, 70);
    }
    
    public void blueShift() {
        colour = Color.blue;
        x = (int) (Math.random() * 300);
        y = (int) (Math.random() * 200);
        repaint();
    }
}

我将 blueshift() 方法连接到 JFrame 类上的 ActionListener,所以我知道如何在命令中更改颜色和位置,但是一旦程序开始运行,我不知道如何在不删除第一个方块的情况下添加新方块.

标签: javaswinggraphicsjpanelrepaint

解决方案


推荐阅读