java颜色网格问题

标签 java swing jbutton

<分区>

我的代码设置了一个 6x6 的 JButton 数组,当您按下其中一个 JButton 时,会弹出一个 6x1 JDialog 框,提供 6 种颜色选择。当按下其中一个时,单击以打开 JDialog 框的方 block 会更改颜色。

我想写一段代码,这样在任何行/列中,每种颜色只能有一个方 block 。在 minut 中,我的 boolean 值会阻止您将相同的颜色设置为相同的正方形(因为当您单击它时,如果它是任何其他颜色,它会变为黑色)。

代码如下。任何帮助都感激不尽。谢谢

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.sql.*;
public class Grid5 extends JFrame implements ActionListener
{
        private ColourChooser paintBox = null;
        public static final int ROW = 6;
        public static final int COLUMN = 6;
        private static Grid5 grid;
        public static final String defaultName = "Black";
        public JButton[][] buttons; //makes an array called buttons
        public static void main(String[] args)// sets up a 6x6 grid
        {
            int rows = 6;
            int cols = 6;
            int size = 600;
            Grid5 grid = new Grid5(rows, cols);
            grid.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            grid.setPreferredSize(new Dimension(size, size));
            grid.pack();
            grid.setLocationRelativeTo(null);
            grid.setVisible(true);
        }
        // main
        public Grid5(int rows, int cols) // makes the 6x6 main grid a grid of JButtons
        {
            int rowSize = 6;
            int colSize = 6;
            int gridSize = 600;
            buttons = new JButton[rowSize][colSize];
            Container pane = getContentPane();
            pane.setLayout(new GridLayout(rows, cols));
            for(int j =0; j < rows; j++){
                for (int i = 0; i < cols; i++) {
                    buttons[j][i] = new JButton("");
                    buttons[j][i].setOpaque(true);
                    buttons[j][i].setBackground(Color.BLACK);
                    buttons[j][i].setActionCommand(j + " " + i);
                    buttons[j][i].setName("Black");
                    buttons[j][i].addActionListener(this);
                    pane.add(buttons[j][i]);
                }
            }
        }               //end of grid constructor

        public void actionPerformed(ActionEvent e) 
        {
            JButton button = (JButton) e.getSource();
            if ( paintBox != null && paintBox.isShowing())//stops more than one paintBox from opening
                paintBox.dispose();
            if( e.getSource() instanceof JButton){
                ((JButton)e.getSource()).setBackground(Color.BLACK);
            } 

            int rows = 6;
            int cols = 1;
            int size = 300;
            paintBox = new ColourChooser(grid, false, button);
            paintBox.setPreferredSize(new Dimension(size/3, size));
            paintBox.pack();
            paintBox.setVisible(true);
        }
}

class ColourChooser extends JDialog
{ 
    private JButton fillRed = new JButton("Red");
    private JButton fillYellow = new JButton("Yellow");
    private JButton fillBlue = new JButton("Blue");
    private JButton fillGreen = new JButton("Green");
    private JButton fillPurple = new JButton("Purple");
    private JButton fillBrown = new JButton("Brown");
    private JButton[] paintButton = {fillRed,fillYellow,fillBlue,fillGreen,fillPurple,fillBrown};
    private Color[] colours = {Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN, new Color(102, 0, 102), new Color(102, 51, 0)};
    private JButton buttonPress;

    private int buttonsLeftRow ;
    private int buttonsLeftColumn ;
    private int row,column;

    public ColourChooser(final Grid5 frame, boolean isModal, JButton button)
    {

        buttonPress = button;
        JPanel panel = new JPanel();
        panel.setLayout(new GridLayout(6, 1));
        for (int i = 0; i < paintButton.length; i++) {
            paintButton[i].setOpaque(true);
            paintButton[i].addActionListener(buttonAction);
            paintButton[i].setForeground(new Color(100,100,100));
            paintButton[i].setBackground(colours[i]);
            panel.add(paintButton[i]);
        }
        add(panel);
        pack();
    }
    private ActionListener buttonAction = new ActionListener()
    {
        public void actionPerformed(ActionEvent a)
        {
            JButton fill = (JButton) a.getSource(); 
            if(fill == fillRed){
                String colour = "Red";
                if(checkColoursRow(colour)){
                    buttonPress.setBackground(Color.RED);
                    buttonPress.setName("Red");
                    dispose();
                }
            }
            if(fill == fillYellow){
                String colour = "Yellow";
                if(checkColoursRow(colour)){
                    buttonPress.setBackground(Color.YELLOW);
                    buttonPress.setName("Yellow");
                    dispose();
                }
            }
            if(fill == fillBlue){
                String colour = "Blue";
                if(checkColoursRow(colour)){
                    buttonPress.setBackground(Color.BLUE);
                    buttonPress.setName("Blue");
                    dispose();
                }
            }
            if(fill == fillGreen){
                String colour = "Green";
                if(checkColoursRow(colour)){
                    buttonPress.setBackground(Color.GREEN);
                    buttonPress.setName("Green");
                    dispose();
                }
            }
            if(fill == fillPurple){
                String colour = "Purple";
                if(checkColoursRow(colour)){
                    buttonPress.setBackground(new Color(102, 0, 102));
                    buttonPress.setName("Purple");
                    dispose();
                }
            }
            if(fill.equals(fillBrown)){
                String colour = "Brown";
                if(checkColoursRow(colour)){
                    buttonPress.setBackground(new Color(102, 51, 0));
                    buttonPress.setName("Brown");
                    dispose();
                }
            } 
        }
    };

    private boolean checkColoursRow(String colour){
        String command = buttonPress.getActionCommand();
        String[] array = command.split(" ");
        int row = Integer.parseInt(array[0]);
         int column = Integer.parseInt(array[1]); 

        for(int i = 0; i<Grid5.COLUMN; i++){
            if (i != row)
            {
                if(buttonPress.getName().equals(colour))
                return false;   
            }
        }


        for (int i = 0; i  < Grid5.ROW; i++)
        {
            if (i != column)
            {
                if (buttonPress.getName().equals(colour))
                    return false;
            }   
        }
        return true;

        }
}

最佳答案

你快到了,只是少了一点点

第 1 步: 您需要将当前初始化的 Grid5 对象的引用传递给 ColorChooser。 为此,更改行

        paintBox = new ColourChooser(grid, false, button);

        paintBox = new ColourChooser(this, false, button);

因为变量 grid 从未被初始化,而 this 指的是当前 Grid5 对象,它将被初始化。 在 ColourChooser 中声明一个类型为 Grid5 的变量作为 Grid5 框架;

第 2 步: 在 ColourChooser

的构造函数中

public ColourChooser(最终的 Grid5 框架,boolean isModal,JButton 按钮)

将参数frame赋值给局部变量as this.frame = fame

这样,您就可以在颜色选择器中引用网格及其按钮

一次,完成,

第 3 步:在 ColourChooser 中以类似 checkColoursRow 的行实现一个方法,以实现您正在寻找的内容。总是好的consider naming for methods that return boolean. .您可能会注意到,它提高了可读性并避免了混淆。

所以,一个方法可能是这样的(你可以改进下面的代码,为了清楚起见,我给出了详细的实现):

private boolean hasColorInRowOrCol(String color){
    String command = buttonPress.getActionCommand();
    String[] array = command.split(" ");
    int row = Integer.parseInt(array[0]);
    int column = Integer.parseInt(array[1]);  
    for(int cols=0; cols < Grid5.COLUMN;cols++) {
            //frame refers to currently initialized Grid5 object
        if(frame.buttons[row][cols].getName().equals(color)){
            return true;
        }
    }
    for(int rows=0;rows < Grid5.ROW; rows++){
            //frame refers to currently initialized Grid5 object
        if(frame.buttons[rows][column].getName().equals(color)){
            return true;
        }
    }
    return false;
}

以上方法基本上适用于当前行/列,并检查颜色是否设置为框架中任何按钮的名称。

第 4 步: 最后一部分是在您的 ActionListener buttonAction 中调用此方法,如下例所示:

  JButton fill = (JButton) a.getSource(); 
    if(fill == fillRed){
        String colour = "Red";
        if(!hasColorInRowOrCol(colour)){
            buttonPress.setBackground(Color.RED);
            buttonPress.setName("Red");
            dispose();
        }
    }

关于java颜色网格问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9936283/

相关文章:

java - 带有Gradle和TestNG的FarmIntegrationTest无法运行?

java - 将 JFrame 与 pack() 结合使用

Java如何刷新jlist中的sql结果

java - 在 Java 中,每次我向 JPanel 添加不止一个东西时,第二个东西没有被创建?

javascript - 使用 Cordova 和 JavaScript 从 android 麦克风获取音频数据(不使用 getUserMedia)

java - 通过在编译时进行验证来改进构建器模式

java - 在 LAMP 系统上与 R(R 项目)、MySQL 和 Java 通信的最有效方式是什么?

java - 可以运行的 swing 工作线程的最大数量是多少

java - 当按下 JButton 时,JTable 第二次变为空白

java - JButton 退出 JPanel