61586

How to set the color of JButtons in an array in java?

Suppose there is an array of the name buttons: private JButton buttons[] = new JButton[9]; How can I set the color of all the buttons in this array to blue?

This is my entire code: It is a game of Tic Tac Toe with the use of buttons.

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

Answer1:

You need to reset the button color to blue in the reset method's for loop:

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

Here's what the resulting application looks like on my machine and a Mac OSX machine. The buttons change to white after being selected:

<img src="https://i.stack.imgur.com/Z3His.png" alt="enter image description here">   <img src="https://i.stack.imgur.com/EckeM.png" alt="enter image description here">

If you're on Mac OSX, you may also be having problems with the system Look & Feel. You can change this in your main method like this:

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

Answer2:

This is actually a sideffect of the JButton.

The background and content are two different concepts. While you can change the background color, it may not change the content area of the button. In fact, it may act differently under different look and feels.

Instead, use JLabel, it's much easier to control...

<img src="https://i.stack.imgur.com/aevyF.png" alt="enter image description here">

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

The only other choice you might have is to create an implementation of the button that is capable of only painting the background color, this would require you to extend from AbstractButton, but to be honest, that's a lot of work...

Answer3:

@808sound is on the right track - some of the standard look and feels (e.g. Windows) make it weird /hard / difficult to change the color of buttons.

At the start of your program, try setting the LAF via

UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());

More details here

Recommend

  • vim: change the status line color in insert mode
  • ListView styling a selected item text-fill - JavaFX 8 MAGIC or BUG?
  • Android: finish() of CountDownTimer is called even if cancel() is called
  • Alternating colors in GPX-Tracks
  • Change form color in ASP.NET
  • How to set the color of JButtons in an array in java?
  • Setting rowcount and column count for grid layout dynamically
  • How do I create a bitmap image as spritefont with multiple character regions?
  • How to interchange between 2 timers? in Java GUI
  • Exception in thread “AWT-EventQueue-0” java.lang.NullPointerException if-statement
  • How to use Swing Timer ActionListener
  • How to make the JDialog invisible when the JProgressBar reaches 100%?
  • JPanel and JButton, cannot figure how to layout 2 simple buttons
  • GUI not updating despite use of validate()
  • Java pong can't move both paddles at once
  • What is sun.awt.windows.WToolkit?
  • How can a flex item keep the same dimensions when it is forced to a new row?
  • UIButton Borders Function Only Gives Back White Borders
  • JTextArea setText(veryLongString) is taking too much time
  • Java making confirming exit
  • Responsive left sidebar open close
  • How to modify the colors in the legend of a plot using a fill gradient?
  • Android fill_parent issue
  • JFileChooser in front of fullscreen Swing application
  • jquery mobile loadPage not working
  • Properly structure and highlight a GtkPopoverMenu using PyGObject
  • How can I get HTML syntax highlighting in my editor for CakePHP?
  • JTable with a ScrollPane misbehaving
  • Angular 2 constructor injection vs direct access
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • python draw pie shapes with colour filled
  • sending mail using smtp is too slow
  • Busy indicator not showing up in wpf window [duplicate]
  • costura.fody for a dll that references another dll
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • Observable and ngFor in Angular 2
  • How can I use `wmic` in a Windows PE script?
  • UserPrincipal.Current returns apppool on IIS
  • java string with new operator and a literal