mevada.yogesh mevada.yogesh - 1 year ago 78
Java Question

Java synth - How to apply solid color to button background

I am trying to obtain simple flat button using synth xml in Java. This button should contain solid color background and text with no other effects.

I have checked some tutorials and successfully implemented below solution where I will need to provide the solid color background image for the button.

<imagePainter method="buttonBackground" path="images/button_press.png" sourceInsets="10 10 10 10"/>
<font name="Dialog" size="16"/>
<color type="TEXT_FOREGROUND" value="#FFFFFF"/>

But as per synth documentation here I should be able to provide the Background color to the button instead of using an image. I have tried below XML settings for the same. But it is not applying any background to buttons. Whereas it is applying provided color to text.

<font name="Verdana" size="14"/>
<color value="#FF0000" type="BACKGROUND"/>
<color value="#000000" type="TEXT_FOREGROUND"/>

Can anyone check and help me find out the mistake I have done or there is any other solution for this?

Answer Source

I guess you would need to use <opaque value="true" /> to paint the JButton's background:


  <style id="default">
    <font name="Dialog" size="16" /> 
  <bind style="default" type="region" key=".*" />

  <style id="ButtonTest">
    <opaque value="true" />
    <insets top="10" bottom="10" left="10" right="10" />
      <font name="Verdana" size="14" />
      <color type="BACKGROUND" value="#FF0000" />
      <color type="TEXT_FOREGROUND" value="#000000" />
    <state value="MOUSE_OVER">
      <color type="BACKGROUND" value="ORANGE" />
      <color type="TEXT_FOREGROUND" value="WHITE" />
    <state value="PRESSED">
      <color type="BACKGROUND" value="GREEN" />
      <color type="TEXT_FOREGROUND" value="WHITE" />
  <bind style="ButtonTest" type="region" key="Button" />

import java.awt.*;
import javax.swing.*;
import javax.swing.plaf.synth.*;

public class SynthButtonTest {
  public JComponent makeUI() {
    JPanel p = new JPanel();
    p.add(new JButton("JButton1"));
    p.add(new JButton("JButton2"));
    p.add(new JButton("JButton3"));
    return p;
  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
      try {
        Class<?> c = SynthButtonTest.class;
        SynthLookAndFeel synth = new SynthLookAndFeel();
        synth.load(c.getResourceAsStream("button.xml"), c);
      } catch (Exception ex) {
      JFrame f = new JFrame();
      f.getContentPane().add(new SynthButtonTest().makeUI());
      f.setSize(320, 240);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download