JButton background image

限于喜欢 提交于 2019-12-03 08:20:17

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...

Instead of determining the button clicked in the action listener, I would use an adapter pattern:

one.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent arg0) {
        handleClick("one");
    }        
});

where handleClick can still be the handler for all your buttons.

i want to get that value and use it on action listener.

You use the action command for this:

one.setActionCommand("1");

However it is better to use the actual text that you want to insert into your display component. Then you can share the ActionListener on all you buttons by using code like:

ActionListener clicked = new ActionListener() 
{
    @Override
    public void actionPerformed(ActionEvent e) {
        String text = e.getActionCommand()
        // displayComponent.appendText(text);
    }        
};

one.addActionListener(clicked);
two.addActionListener(clicked);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!