【发布时间】:2021-03-07 11:55:31
【问题描述】:
如何在swing,java中设置按钮的活动背景颜色? 活动背景颜色是按钮被单击时的背景颜色。
【问题讨论】:
如何在swing,java中设置按钮的活动背景颜色? 活动背景颜色是按钮被单击时的背景颜色。
【问题讨论】:
JButton 示例演示背景颜色改变,同时移动鼠标并点击按钮:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
public class JButtonBGColorDemo {
class ColorTestButton extends JButton {
private Color hoverBackgroundColor;
private Color pressedBackgroundColor;
public ColorTestButton() {
this(null);
}
public ColorTestButton(String text) {
super(text);
super.setContentAreaFilled(false);
}
@Override
protected void paintComponent(Graphics g) {
if (getModel().isPressed()) {
g.setColor(pressedBackgroundColor);
} else if (getModel().isRollover()) {
g.setColor(hoverBackgroundColor);
} else {
g.setColor(getBackground());
}
g.fillRect(0, 0, getWidth(), getHeight());
super.paintComponent(g);
}
@Override
public void setContentAreaFilled(boolean b) {
}
public Color getHoverBackgroundColor() {
return hoverBackgroundColor;
}
public void setHoverBackgroundColor(Color hoverBackgroundColor) {
this.hoverBackgroundColor = hoverBackgroundColor;
}
public Color getPressedBackgroundColor() {
return pressedBackgroundColor;
}
public void setPressedBackgroundColor(Color pressedBackgroundColor) {
this.pressedBackgroundColor = pressedBackgroundColor;
}
}
protected void createUIDesign() {
JFrame frame = new JFrame("Test button");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final ColorTestButton btn = new ColorTestButton("Color Test Button");
btn.setForeground(new Color(0, 135, 200).brighter());
btn.setHorizontalTextPosition(SwingConstants.CENTER);
btn.setBorder(null);
btn.setBackground(new Color(3, 59, 90));
btn.setHoverBackgroundColor(new Color(3, 59, 90).brighter());
btn.setPressedBackgroundColor(Color.PINK);
frame.add(btn);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JButtonBGColorDemo().createUIDesign();
}
});
}
}
【讨论】:
如果您想对所有按钮执行此操作,您可以使用 LAF 更改默认设置:
UIManager.put("Button.select", Color.RED);
上述代码应在创建组件之前执行。
【讨论】: