java - 使用 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,所以我知道如何在命令中更改颜色和位置,但是一旦程序开始运行,我不知道如何在不删除第一个方块的情况下添加新方块.
解决方案
推荐阅读
- cassandra - 更新表上的压缩 min_threshold 是否会导致 sstables 被重写?
- ansible - ansible-vault 可以用来向 vault 添加新的秘密吗
- javascript - couchdb 简化为矩阵
- android - 如何在后台从 url 下载图像并将其加载到 ImageView 的 onPostExecute
- laravel - 静态控制器多路由/单控制器
- ios - 函数体运行的次数与我展示 ViewController 的次数一样多
- python - 楼层划分操作员的结果差异
- r - 我需要复制一些列并以有效的方式在另一个列中添加一个 rnorm
- vba - 批处理文件按住 shift 键突出显示
- xamarin.forms - Xamarin.Forms 推送通知的传输非常不可靠(迟到或根本不传输)