Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JButton background image

Hi i am trying to implement Action listener for JButton and code look like following:

ImageIcon imageForOne = new ImageIcon(getClass().getResource("resources//one.png"));
one = new JButton("",imageForOne);
one.setPreferredSize( new Dimension(78, 76));
one.addActionListener(myButtonHandler);

Using the above JButton it looks fineSee the image below for button 1

When i add specific value to button for e.g.

ImageIcon imageForOne = new ImageIcon(getClass().getResource("resources//one.png"));
//Check this
one = new JButton("one",imageForOne);
one.setPreferredSize( new Dimension(78, 76));
one.addActionListener(myButtonHandler);

It look like the following image

Check button 1

Is there any way i can avoid this and set the value too.

Thanks for your help in advance.

like image 707
usrNotFound Avatar asked Jun 14 '13 14:06

usrNotFound


1 Answers

Personally, I would be using the Action API.

It will allow you defined a hierarchy of action commands (if that's what you want) as well as define self contained response to the commands.

You could...

public class OneAction extends AbstractAction {
    public OneAction() {
        ImageIcon imageForOne = new ImageIcon(getClass().getResource("resources//one.png"));
        putValue(LARGE_ICON_KEY, imageForOne);
    }

    public void actionPerfomed(ActionEvent evt) {
        // Action for button 1
    }
}

Then you would simply use with your button...

one = new JButton(new OneAction());
one.setPreferredSize( new Dimension(78, 76));

For example...

like image 93
MadProgrammer Avatar answered Oct 21 '22 12:10

MadProgrammer