java - 按下按钮时如何更改按钮文本颜色和背景颜色
问题描述
我正在尝试使用 Java 中的 Swing UI 在按下鼠标按钮时更改按钮背景颜色和文本(前景)颜色。我的主要课程非常简单明了:
public class Main {
public static void main(String[] args) {
SynthLookAndFeel laf = new SynthLookAndFeel();
try {
laf.load(Main.class.getResourceAsStream("/styles.xml"), Main.class);
} catch (ParseException e) {
e.printStackTrace();
}
try {
UIManager.setLookAndFeel(laf);
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
JFrame frame = new JFrame("Not hello world");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.setLocation(50, 50);
frame.setLayout(new FlowLayout());
frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.setVisible(true);
}
}
加载的 XML Synth 样式文件如下:
<synth>
<style id="basicStyle">
<font name="Verdana" size="16"/>
<state>
<color value="#eeeeee" type="BACKGROUND"/>
<color value="#000000" type="FOREGROUND"/>
</state>
</style>
<bind style="basicStyle" type="region" key=".*"/>
<style id ="button_style">
<state value="PRESSED">
<color value="#666666" type="FOREGROUND" />
<color value="#aaaaaa" type="BACKGROUND" />
</state>
</style>
<bind style="button_style" type="region" key="button"/>
但我得到的只是屏幕上带有黑色文本和灰色背景的按钮。按下按钮时,没有任何反应:
我有什么办法可以实现这种行为?
解决方案
Synth
您的文件中有一些问题:
它没有关闭
</synth>
如果您没有
opaque="true"
在其中设置,默认情况下您JButton
将是透明的(即您的背景将不可见)。我不完全确定为什么,但是要使前景字体颜色在状态更改时更改,您需要使用
TEXT_FOREGROUND
而不是FOREGROUND
键。
我从您的文件中更改了一些颜色,因为它们不太明显,但您的文件应该类似于:
<synth>
<style id="basicStyle">
<font name="Verdana" size="16" />
<state>
<color value="#eeeeee" type="BACKGROUND" />
<color value="#000000" type="FOREGROUND" />
</state>
</style>
<bind style="basicStyle" type="region" key=".*" />
<style id="button_style">
<opaque value="true" />
<insets top="4" left="4" right="4" bottom="4" />
<state>
<color value="blue" type="TEXT_FOREGROUND" />
<color value="#ffffff" type="BACKGROUND" />
</state>
<state value="PRESSED">
<color value="white" type="TEXT_FOREGROUND" />
<color value="#aaaaaa" type="BACKGROUND" />
</state>
</style>
<bind style="button_style" type="region" key="button" />
</synth>
推荐阅读
- python - 当有多个同名对象时更新 JSON - Python
- azure-devops - 如何找出:拉取请求是否涵盖给定分支中的所有提交?
- c# - 我可以在方法结束时安全地删除 await Task.CompletedTask 调用吗?
- c# - C# UWP 中的 TouchMajor 和 TouchMinor
- python - 如何使密集图上的所有点在 matplotlib 中可见?
- mongodb - 如何在MongoDB中返回数组匹配条件的元素
- javascript - 自定义光标悬停时如何更改文本颜色
- c++ - 为什么某些 STL 容器(堆栈、队列、优先级队列)不支持迭代器?
- php - 如何在 PHP 中发送此 CURL
- python - 如何以特殊方式对熊猫数据框进行排序