Is there a way to store data in a JButton?

后端 未结 2 612

My program currently adds an image to a List, which it then creates a Jbutton dynamically storing a thumbnail. Like found here. although the images are added as the user sel

相关标签:
2条回答
  • 2020-12-20 07:46

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

    0 讨论(0)
  • 2020-12-20 07:46

    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;
    
    0 讨论(0)
提交回复
热议问题