0

I want to create button with custom look and feel. I have got different images to be set as background of button for normal, mouse over, mouse click, button disabled etc. I have created my own class, extending javax.swing.JButton and overrides paintComponent method. How can i change my button background for all the above given states.

4 Answers 4

4

In addition to Steve De Caux's answer, you can:

  1. Add a MouseListener which changes an enum variable, let's call it state on your extended JButton
  2. In your overridden paintComponent take into consideration the current state and paint different backgrounds. Like

    if (!getModel().isEnabled()) {
    } else if (state == ButtonState.MOUSE_OVER) {
    } else if (state == ButtonState.MOUSE_CLICKED) {   
    }
    
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much Bozho... Its working fine... I am so happy.. thanks a lot
Then why haven't you accepted an answer so people know the question has been answered?
3

JButton has a series of simple set methods for rollover, pressed, selected, disabled and disabled selected states - for example

button.setPressedIcon(new ImageIcon("images/button-down.png")

the other methods are :

button.setRolloverIcon()
button.setSelectedIcon()
button.setRolloverSelectedIcon()
button.setDisabledIcon()
button.setDisabledSelectedIcon()

...have fun !

By the way, O'Reilly has a fun book called Swing Hacks with lots of little goodies for playing with swing : Swing Hacks

Comments

2

You could create a custom button UI delegate. This blog entry: http://blog.elevenworks.com/?p=4 has an example for a custom tabbed pane, but the principle is the same. Extend BasicButtonUI, implement the custom rendering your want for the button, and then call setUI() on the button.

This will probably take longer to implement than using the existing button API methods to change the appearance, but it gives you a lot more control.

Comments

0
ImageIcon icon = new ImageIcon("images/icon.gif");
JButton button = new JButton(icon);

1 Comment

Thanks for answering yankee2905. This code is to set the icon image on the button. I want to know how can i remove button's default look and feel and add my own images for mouseover, mouse click and disabled states??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.