This question already has an answer here:
- Java Swing button colors [duplicate] 1 answer
I have a question about setting the background color to JButton
.
It seems that the this method only changes the color of the border. Here is the difference (left is jButton
):
Is there a way to make the background the same?
I'm using setLookAndFeel
on Windows 8.
This will work with either the Metal (default) or Windows PLAFs.
import java.awt.*;
import javax.swing.*;
class ColoredButton {
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
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);
}
}
Use .setOpaque(true) on the button.
来源:https://stackoverflow.com/questions/18165160/setting-background-color-to-jbutton