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

Miniature Pixel art program using JButtons

我最近刚接触 Java,但还是个菜鸟。我创建了一个 9x9 的 JPanels 面板,使用 for 循环来添加按钮。我将如何创建一个允许我选择不同颜色的动作侦听器,这些颜色将在单击时显示为 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 语句放入名为 determineColor() 或类似名称的新方法中。