5

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.

4

3 回答 3

5

就个人而言,我会使用ActionAPI

它将允许您定义动作命令的层次结构(如果这是您想要的)以及定义对命令的自包含响应。

你可以...

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

然后你只需使用你的按钮......

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

例如...

于 2013-06-15T00:46:11.767 回答
4

我不会确定在动作侦听器中单击的按钮,而是使用适配器模式:

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

wherehandleClick仍然可以作为所有按钮的处理程序。

于 2013-06-14T14:13:35.077 回答
3

我想获得该值并将其用于动作侦听器。

为此,您可以使用 action 命令:

one.setActionCommand("1");

但是,最好使用要插入到显示组件中的实际文本。然后,您可以使用以下代码在所有按钮上共享 ActionListener:

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

one.addActionListener(clicked);
two.addActionListener(clicked);
于 2013-06-14T15:02:07.793 回答