【问题标题】:How to set the color of JButtons in an array in java?如何在java中的数组中设置JButtons的颜色?
【发布时间】:2012-12-16 11:14:42
【问题描述】:

假设有一个名称按钮数组:
私有 JButton 按钮[] = new 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();
   }
}

【问题讨论】:

  • 为了这个确切的用途,我会将彩色图标放在按钮中,而不是知道如何绘制 XO 或没有符号。 :)

标签: java swing jbutton background-color


【解决方案1】:

这实际上是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();
            }
        });
    }
}

您可能拥有的唯一其他选择是创建一个只能绘制背景颜色的按钮实现,这需要您从AbstractButton 扩展,但老实说,这是很多工作。 ..

【讨论】:

    【解决方案2】:

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

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

    这是生成的应用程序在我的机器和 Mac OSX 机器上的样子。按钮被选中后变为白色:

    如果您使用的是 Mac OSX,您可能还会遇到系统外观问题。您可以像这样在 main 方法中更改它:

    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();
    }
    

    【讨论】:

    • 嗯,这很奇怪。那么当窗口第一次出现时,上面所有的按钮都是灰色的?当你点击它们时它们会改变颜色吗?
    • 你是如何构建这个项目的?也就是说,您是使用 Eclipse,还是从命令行编译?另外,您使用的是什么版本的 Java?
    • 我正在使用 Eclipse。如何确定我使用的是什么版本的 Java?
    • 在 Eclipse 中,您可以进入“Window”菜单,然后进入 Preferences->Java->Installed JREs。这应该显示一个 JRE 列表,并选中默认的。
    • 嗯。我认为它的 Java SE 7.
    【解决方案3】:

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

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

    UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); 
    

    More details here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-31
      • 2011-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-27
      • 2015-05-17
      • 2017-09-11
      相关资源
      最近更新 更多