我正在尝试使用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"/>
但是我得到的只是屏幕上具有黑色文本和灰色背景的按钮。当按下按钮时,什么也没发生:
有什么办法可以实现这种行为?
答案 0 :(得分:1)
您的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>