当前位置: 首页 > 知识库问答 >
问题:

如何在java中设置数组中JButtons的颜色?

单于钊
2023-03-14

假设有一个名称按钮数组:
私有JButton按钮[]=新JButton[9]
如何将此数组中所有按钮的颜色设置为蓝色?

这是我的全部代码:这是一个使用按钮的井字游戏。

import java.awt.*; 
import java.awt.event.*;
import javax.swing.*;
import java.awt.BorderLayout;

public class TicTacToe implements ActionListener {
private JButton buttons[] = new JButton[9];
private JFrame window = new JFrame("Tic Tac Toe");
private boolean win = false;
private int count = 0;
private int Xwins = 0, Owins = 0;
private String letter = "";
private int[][] winCombinations = new int[][] {
        {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
        {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //vertical wins
        {0, 4, 8}, {2, 4, 6}                     //diagonal wins
};
String name1 = JOptionPane.showInputDialog("Please enter first player's name");
String name2 = JOptionPane.showInputDialog("Please enter second player's name");

public TicTacToe(){
    JOptionPane.showMessageDialog(null,"Remember Player 1 is X and Player 2 is O.");
    window.setSize(300,300);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    window.setLayout(new GridLayout(3,3));
    window.setVisible(true);


      for(int i=0; i<=8; i++){
          buttons[i] = new JButton();
          window.add(buttons[i]);
          buttons[i].addActionListener(this);
          buttons[i].setBackground(Color.MAGENTA);
  }
      for (JButton button: buttons) {
           button.setBackground(Color.BLUE);
        }

}

public void actionPerformed(ActionEvent event) {
        count++;
        if(count % 2 == 0){
            letter = "O";

        }else{
            letter = "X";
        }
         JButton pressedButton = (JButton)event.getSource(); 
         pressedButton.setText(letter);
         pressedButton.setEnabled(false);
         pressedButton.setBackground(Color.WHITE);


    //Determine who won
    for(int i=0; i<=7; i++){
        if( buttons[winCombinations[i][0]].getText().equals(buttons[winCombinations[i][1]].getText()) && 
                buttons[winCombinations[i][1]].getText().equals(buttons[winCombinations[i][2]].getText()) && 
                buttons[winCombinations[i][0]].getText() != ""){
                win = true;
            }
        }
        if(win == true){
            if(letter == "X"){
                JOptionPane.showMessageDialog(null, name1 + " wins the game!");
            }else{
                JOptionPane.showMessageDialog(null, name2 + " wins the game!");
            }
            playAgain();
        }else if(count == 9 && win == false){
            JOptionPane.showMessageDialog(null, "The game is tied!");
            playAgain();
        }
    } 

public void playAgain(){
    if(letter == "X"){
        Xwins++;
    }else{
        Owins++;
    }
    JOptionPane.showMessageDialog(null, name1 + " has won this many times: " + Xwins);
    JOptionPane.showMessageDialog(null, name2 + " has won this many times: " + Owins);
    int response = JOptionPane.showConfirmDialog(null, "Would you like to play again?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

    if(response == JOptionPane.YES_OPTION){
        reset();
    }else{
        System.exit(0);
    }
}

  public void reset() {
      for(int i = 0; i<=8; i++) {
              buttons[i].setText("");
              buttons[i].setEnabled(true); 
      }
      win = false;
      count = 0;
  }  

public static void main(String[] args){
    TicTacToe play = new TicTacToe();
   }
}

共有3个答案

丌官晔
2023-03-14

@808sound在正确的轨道上-一些标准的外观和感觉(例如Windows)使按钮的颜色变得奇怪/困难/难以更改。

在程序开始时,尝试通过设置LAF

UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); 

此处提供更多详细信息

樊宏义
2023-03-14

您需要在重置方法的循环中将按钮颜色重置为蓝色:

buttons[i].setBackground(Color.blue);

下面是在我的机器和Mac OSX机器上生成的应用程序的外观。选择后,按钮变为白色:

public static void main(String[] args){
   try {
      // Set cross-platform Java L&F (also called "Metal")
      UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
      // alternatively, the following should load the default L&F for your system
      //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
   } catch (Exception e) {}

   TicTacToe play = new TicTacToe();
}
黄博艺
2023-03-14

这实际上是JButton的副作用。

背景和内容是两个不同的概念。虽然您可以更改背景色,但它可能不会更改按钮的内容区域。事实上,在不同的外观和感觉下,它的行为可能会有所不同。

相反,使用JLabel,它更容易控制。。。

public class TicTacToe implements ActionListener {

    private JLabel labels[] = new JLabel[9];
    private JFrame window = new JFrame("Tic Tac Toe");
    private boolean win = false;
    private int count = 0;
    private int Xwins = 0, Owins = 0;
    private String letter = "";
    private int[][] winCombinations = new int[][]{
        {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, //horizontal wins
        {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, //vertical wins
        {0, 4, 8}, {2, 4, 6} //diagonal wins
    };
    String name1 = JOptionPane.showInputDialog("Please enter first player's name");
    String name2 = JOptionPane.showInputDialog("Please enter second player's name");

    public TicTacToe() {
        JOptionPane.showMessageDialog(null, "Remember Player 1 is X and Player 2 is O.");
        window.setSize(300, 300);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setLayout(new GridLayout(3, 3));
        window.setVisible(true);

        MouseHandler handler = new MouseHandler();

        for (int i = 0; i <= 8; i++) {
            labels[i] = new JLabel();
            labels[i].setOpaque(true);
            labels[i].setBorder(new LineBorder(Color.LIGHT_GRAY));
            labels[i].setHorizontalAlignment(JLabel.CENTER);
            window.add(labels[i]);
            labels[i].addMouseListener(handler);
            labels[i].setBackground(Color.MAGENTA);
        }
//        for (JButton button : buttons) {
//            button.setBackground(Color.BLUE);
//        }

    }

    public void actionPerformed(ActionEvent event) {
    }

    public void playAgain() {
        if (letter == "X") {
            Xwins++;
        } else {
            Owins++;
        }
        JOptionPane.showMessageDialog(null, name1 + " has won this many times: " + Xwins);
        JOptionPane.showMessageDialog(null, name2 + " has won this many times: " + Owins);
        int response = JOptionPane.showConfirmDialog(null, "Would you like to play again?", "Confirm", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);

        if (response == JOptionPane.YES_OPTION) {
            reset();
        } else {
            System.exit(0);
        }
    }

    public void reset() {
        for (int i = 0; i <= 8; i++) {
            labels[i].setText("");
            labels[i].setEnabled(true);
        }
        win = false;
        count = 0;
    }

    public class MouseHandler extends MouseAdapter {

        @Override
        public void mouseClicked(MouseEvent event) {
            count++;
            if (count % 2 == 0) {
                letter = "O";

            } else {
                letter = "X";
            }
            JLabel pressedLabel = (JLabel) event.getSource();
            pressedLabel.setText(letter);
            pressedLabel.setEnabled(false);
            pressedLabel.setBackground(Color.WHITE);


            //Determine who won
            for (int i = 0; i <= 7; i++) {
                if (labels[winCombinations[i][0]].getText().equals(labels[winCombinations[i][1]].getText())
                                && labels[winCombinations[i][1]].getText().equals(labels[winCombinations[i][2]].getText())
                                && labels[winCombinations[i][0]].getText() != "") {
                    win = true;
                }
            }
            if (win == true) {
                if (letter == "X") {
                    JOptionPane.showMessageDialog(null, name1 + " wins the game!");
                } else {
                    JOptionPane.showMessageDialog(null, name2 + " wins the game!");
                }
                playAgain();
            } else if (count == 9 && win == false) {
                JOptionPane.showMessageDialog(null, "The game is tied!");
                playAgain();
            }
        }
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (Exception ex) {
                }

                TicTacToe play = new TicTacToe();
            }
        });
    }
}

您唯一的其他选择可能是创建一个只能够绘制背景色的按钮实现,这需要您从抽象按钮扩展,但老实说,这需要大量的工作。。。

 类似资料:
  • 我想设置图表的数据颜色,所以我找到了MPAndroidchart,但示例是由Java制作的,而不是Kotlin。 这是我的Kotlin来源。如何更改颜色 此外,我想在条形图中的条形图下方制作标签(如第一张图片),请帮帮我。。T\u T 代码结果:

  • 我想将图标设置为,我从这个网站下载了图标:FlatIcon 现在我想设置此图标的颜色,但当使用时,只需为背景添加颜色,而不是设置为图标! 当使用时,我可以用此代码设置图标的颜色:。 如何将图标的颜色设置为,例如?谢谢大家

  • 我试图设置文本背景颜色使用 是红色、绿色、蓝色值来自数据库,基于值set编程时,它的颜色为暗绿色,但我运行程序时它将显示红色

  • 我的需要是,为一个屏幕的应用程序,其中有白色的背景,并在白色的背景,我必须显示Textinputlayout提示,文本,编辑文本颜色在黑色字体。

  • 本文向大家介绍如何在HTML中设置背景颜色?,包括了如何在HTML中设置背景颜色?的使用技巧和注意事项,需要的朋友参考一下 要在HTML中设置背景颜色,请使用style属性。style属性指定元素的内联样式。该属性与HTML <body>标记以及CSS属性background-color一起使用。HTML5不支持<body>标记的bgcolor属性,因此CSS样式用于添加背景色。HTML5中不推荐