Reputation: 2792
I want to change the Java Swing JButton's background color.
The original button looks like this:
After I change background color of this button, it looks like this:
The orginal one has the "button" look and feeling. However, the yellow one just looks like a yellow plain background with a some text on top.
Question: Is there any easy way that I change the this specific Jbutton's background color but keep the look&feel?
P.S. I know I can make an image and attach to the button. However, the button size will not be always the same so the image may not be a good idea. Is there any other way I can just simply add some codes such as add some border, margin etc so that it has more button-feel?
Update:
I want the button look like a button after I change the background color. It does not matter if I need to add gradient background or do something else. I am looking for a easiest way to do it.
Upvotes: 0
Views: 1495
Reputation: 7560
Use this external api.Simply put the line
UIManager.setLookAndFeel("com.jtattoo.plaf.aluminium.AluminiumLookAndFeel");
as first line in main method
Upvotes: 0
Reputation: 24998
You can have a GradientPaint
as your background.
public final class JGradientButtonDemo {
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
@Override
public void run() {
createAndShowGUI();
}
});
}
private static void createAndShowGUI(){
final JFrame frame = new JFrame("Gradient JButton Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new FlowLayout());
frame.add(JGradientButton.newInstance());
frame.setSize(new Dimension(300, 150)); // used for demonstration
//frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
private static final class JGradientButton extends JButton{
private JGradientButton(){
super("Gradient Button");
setContentAreaFilled(false);
setFocusPainted(false); // used for demonstration
}
@Override
protected void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g.create();
g2.setPaint(new GradientPaint(
new Point(0, 0),
Color.WHITE,
new Point(0, getHeight()),
Color.PINK.darker()));
g2.fillRect(0, 0, getWidth(), getHeight());
g2.dispose();
super.paintComponent(g);
}
public static final JGradientButton newInstance(){
return new JGradientButton();
}
}
}
Example taken from Change JButton gradient color, but only for one button, not all
Upvotes: 1