Java Swing Button Colors

How to set background color of a button in Java GUI?

Check out JButton documentation. Take special attention to setBackground and setForeground methods inherited from JComponent.

Something like:

for(int i=1;i<=9;i++)
{
JButton btn = new JButton(String.valueOf(i));
btn.setBackground(Color.BLACK);
btn.setForeground(Color.GRAY);
p3.add(btn);
}

Java Swing button colors

Here is a question and several answers related to flashing a component.

Addendum: You can learn more in the article How to Use Buttons. In particular, you can use setForeground() to change the color of a button's text, but the corresponding setBackground() doesn't read well on some platforms. Using a Border is one alternative; a colored panel, shown below, is another.

Sample Image

package overflow;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class ButtonTest extends JPanel implements ActionListener {

private static final int N = 4;
private static final Random rnd = new Random();
private final Timer timer = new Timer(1000, this);
private final List<ButtonPanel> panels = new ArrayList<ButtonPanel>();

public ButtonTest() {
this.setLayout(new GridLayout(N, N, N, N));
for (int i = 0; i < N * N; i++) {
ButtonPanel bp = new ButtonPanel(i);
panels.add(bp);
this.add(bp);
}
}

@Override
public void actionPerformed(ActionEvent e) {
for (JPanel p : panels) {
p.setBackground(new Color(rnd.nextInt()));
}
}

private static class ButtonPanel extends JPanel {

public ButtonPanel(int i) {
this.setBackground(new Color(rnd.nextInt()));
this.add(new JButton("Button " + String.valueOf(i)));
}
}

public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {

@Override
public void run() {
JFrame f = new JFrame("ButtonTest");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ButtonTest bt = new ButtonTest();
f.add(bt);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
bt.timer.start();
}
});
}
}

How to Set the Background Color of a JButton on the Mac OS

Have you tried setting JButton.setOpaque(true)?

JButton button = new JButton("test");
button.setBackground(Color.RED);
button.setOpaque(true);

How to update button colors continually [JAVA SWING]

Put the setVisible(true); or revalidate(); after you added your components. Better work with the frame content pane.

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

class Scratch {

public static void main(String[] args) throws InterruptedException {
JFrame jFrame = new JFrame();

jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.setSize(600, 400);
jFrame.setVisible(true);

for (int i = 5; i < 10; ++i) {
jFrame.setContentPane(createPanel(i, i, new int[i][i]));
jFrame.revalidate();
Thread.sleep(1000);
}
}

public static JPanel createPanel(int n, int m, int[][] mat) {
JButton[] buttons = new JButton[n * m];
JPanel jPanel = new JPanel();

jPanel.setLayout(new GridLayout(n, m));

for (int i = 0; i < n * m; i++) {
buttons[i] = new JButton();
}
for (int j = 0; j < n; j++) {
for (int k = 0; k < m; k++) {
int index = k + k * j;

if (mat[j][k] == 0) {
buttons[index].setBackground(Color.BLACK);
}
jPanel.add(buttons[index]);
}
}

return jPanel;
}
}

Cant change java button color after resetting button array

I invoke .revalidate in the fourth line of the method.

That doesn't do anything since there on no components added to the panel. The revalidate() needs to be done AFTER the components have been added.

The displayed panel is not jpanel, the displayed panel is jpanel2, thats why I assign jpanel2 to the value of jpanel in the end of the method.

You can't just change a reference and expect the components to be moved from one panel to another.

The components need to be added to the panel that is added to the GUI.

Edit:

First of all Swing components start with "J". Don't use AWT components (MenuBar, Menu, MenuItem) in a Swing application.

The problem is your LAF:

new MineSweeper();
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

The components are created with the current LAF. When you first create the game, the default LAF is used to create all the buttons (and other components). This LAF allows you to change the background color of the buttons.

However, then you change the LAF. So when you reset the game board the buttons are now created with the System LAF. This LAF apparently does not allow you to change the background color of the button.

This should be easy to test. Create a GUI:

//UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

JButton button = new JButton("testing");
button.setBackground(Color.RED);

JFrame frame = new JFrame("SSCCE");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( button );
frame.pack();
frame.setLocationByPlatform( true );
frame.setVisible( true );

First test the code as above to see if the background of the button changes.

Then uncomment the LAF change and retest.

A possible solution so you are not dependent on the LAF is to use an Icon to represent the background color of the button. Then you can center any text on top of the Icon. Something like:

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

public class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;

public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}

public int getIconWidth()
{
return width;
}

public int getIconHeight()
{
return height;
}

public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}

public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}

public static void createAndShowGUI()
{
JPanel panel = new JPanel( new GridLayout(2, 2) );

for (int i = 0; i < 4; i++)
{
Icon icon = new ColorIcon(Color.RED, 50, 50);
JLabel label = new JLabel( icon );
label.setText("" + i);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);
panel.add(label);
}

JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.setSize(200, 200);
f.setLocationRelativeTo( null );
f.setVisible(true);
}
}

JButton will not display background color

I would eventually like a JButton to change color when pressed

here are two different ways (note JButton has an arrays of colors in UIManager)

  • override events from ButtonModel (ChangeListener or the same methods are implemented e.g. isPressed, isArmed in JButtons API), accelators are valid for mouse and KeyEvens (selection or focusInWindow)

  • override BasicsButtonUI (for real project)

I am using a mac, and I'm wondering if it has something to do with the
default button settings, but I don't know how to change/override
these.

  • depends of Look and Feel that your Java uses (Quaqua - default on OSX or standards by Oracle Metal, Nimbus ...)

How to change button's color?

If you store your buttons in a list that you pass in to the function you will be able to iterate through it and set the background color for each button.

Setting background color to JButton

This will work with either the Metal (default) or Windows PLAFs.

import java.awt.Color;
import javax.swing.*;

class ColoredButton {

public static void main(String[] args) {
Runnable r = () -> {
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}

JButton b1 = new JButton("Button 1");
b1.setBackground(Color.RED);
// these next two lines do the magic..
b1.setContentAreaFilled(false);
b1.setOpaque(true);

JOptionPane.showMessageDialog(null, b1);
};
SwingUtilities.invokeLater(r);
}
}

How to change the background color of a Jbutton on click

If you want to change the background of the button with a persistent color when the user clicks on the button, then you can use setContentAreaFilled(false) on it. Then it is required to reset the opaque property to true because according to the docs of setContentAreaFilled: "This function may cause the component's opaque property to change.", for example:

import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class MainPersist {

private static void createAndShowGUI() {
final JButton button = new JButton("Click to change color");
button.addActionListener(e -> {
button.setContentAreaFilled(false);
button.setOpaque(true); //Reset the opacity.
button.setBackground(Color.CYAN.darker()); //Set your desired color as the background.
});

final JFrame frame = new JFrame("Button bg on click");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(button);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(final String[] args) {
SwingUtilities.invokeLater(MainPersist::createAndShowGUI);
}
}

Otherwise, if you want the button to only change its color when clicked and then return back to normal when released, then take a look at this question which is about exactly that. It has no accepted answers yet (it is very recent as of the time this answer itself is posted), but there is at least one/my answer (which suggests to modify the ButtonUI of the button) and there should be more answers coming I guess.



Related Topics



Leave a reply



Submit