[英]Java Swing keep the button look&feel but background color
I want to change the Java Swing JButton's background color. 我想更改Java Swing JButton的背景颜色。
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? 问题:有什么简便的方法可以更改此特定Jbutton的背景颜色,但保持外观?
PS 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. 我正在寻找一种最简单的方法。
You can have a GradientPaint
as your background. 您可以将GradientPaint
作为背景。
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 示例取自Change JButton渐变颜色,但仅适用于一个按钮,并非全部
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.