如何设置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);
上面的代码应该在你创建组件之前执行。