gpt4 book ai didi

java - 使用 JButtons 的微型像素艺术程序

转载 作者:太空宇宙 更新时间:2023-11-04 11:31:50 25 4
gpt4 key购买 nike

我最近才接触 Java,而且还是个菜鸟。我使用 for 循环创建了一个 9x9 的 JPanel 面板来添加按钮。如何创建一个 Action 监听器,让我可以选择不同的颜色,单击时将显示为 JButton 的背景颜色?我正在尝试制作一个微型像素艺术程序。

最佳答案

它看起来像这样。在此示例中,[row][col] 指网格的行值和列值。请务必创建计数器 (private static int counter = 0;)。否则你会得到一堆错误。这是代码:

JBut[row][col].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

typeOfButton button = (typeOfButton) e.getSource();
int row = button.getRow();
int col = button.getCol();

counter++;
if (counter == 1) {
JBut[row][col].setBackground(Color.RED);
}
else if (counter == 2) {
JBut[row][col].setBackground(Color.ORANGE);
}
else if (counter == 3) {
JBut[row][col].setBackground(Color.YELLOW);
}
else if (counter == 4) {
JBut[row][col].setBackground(Color.GREEN);
}
else if (counter == 5){
JBut[row][col].setBackground(Color.BLUE);
}
else if (counter == 6){
JBut[row][col].setBackground(Color.MAGENTA);
}
else {
JBut[row][col].setBackground(Color.BLACK);
counter = 0; //makes color cycle repeat, starting with red
} //end else
} //end actionPerformed
}); //end ActionListener

显然,执行此操作的简单方法是将巨大的 if 语句放入名为 defineColor() 或类似方法的新方法中。

关于java - 使用 JButtons 的微型像素艺术程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43700319/

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