Is there a way to store data in a JButton?

北城余情 提交于 2019-12-01 13:59:28

One method you can try is to set an action command on the button when it is created. This java tutorial demonstrates this concept is greater detail.

In your case, you would set it like so:

final JButton iconButton = new JButton(icon);
iconButton.setActionCommand("some_unique_identifying_information");

And you can retrieve it in the actionPerformed callback like so:

@Override
public void actionPerformed(ActionEvent e) {
    String actionCommand = iconButton.getActionCommand();
    // ... rest of method
}

Note the use of final on the iconButton. From the looks of your code, the button that fires the event is accessible via the action listener's closure. If you prefer, or cannot use the above method, you can access the button like so:

@Override
public void actionPerformed(ActionEvent e) {
    JButton button = (JButton) e.getSource();
    String actionCommand = button.getActionCommand();
    // ... rest of method
}

Similar to Christian's suggestion in the comments, you can, if you wish, maintain a Map or other data structure in which your unique action command is related to an image. Your map might look like Map<String, ImpImage> (assuming ImpImage is the class of your icon).

Alternatively, the action command may be the string representation of your index value. While it must be stored in String form, once you retrieve it via getActionCommand(), you can parse it back to a number using Integer.parseInt(String).

How about your extend the JButton class.

class MyButton extends JButton{
    public int index;
    MyButton(){super();}
    MyButton(int index){super();this.index=index;}
}

When you need to get the index, cast it back to MyButton and get the index;

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