Reputation: 2354
I'm trying to change the button background color and text (foreground) color while the mouse button is pressed, using Swing UI in Java. My main class is pretty simple and straightforward:
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);
}
}
the loaded XML Synth style file is following:
<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"/>
But all I get is buttons that have black text and gray-ish backround, on the screen. When pressing the buttons, nothing happens:
Any way I can achieve such a behavior?
Upvotes: 2
Views: 821
Reputation: 11143
There are some issues in your Synth
file:
It's not closed with </synth>
If you don't set opaque="true"
in it, by default your JButton
will be transparent (i.e. your background won't be visible).
I'm not entirely sure why, but for the foreground font color to change on state change you need to use TEXT_FOREGROUND
instead of FOREGROUND
key.
I changed some colors from your file as they weren't too visible, but your file should look something like:
<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>
Upvotes: 1