有没有办法在 JButton 中存储数据?

use*_*314 1 java image dynamic jbutton imageicon

我的程序当前将一个图像添加到一个列表中,然后它会创建一个动态存储缩略图的 Jbutton。喜欢在这里找到。尽管图像是在用户选择时添加的。

我遇到的问题是我无法将图像更改为所选的缩略图,因为它们未链接到列表中的图像。有没有办法可以将图像的索引号存储在按钮中,所以当我单击它时,我知道要在列表中显示哪个图像?或者还有其他更智能的方法吗?谢谢。

 //Create thumbnail
    private void createThumbnail(ImpImage image){
        Algorithms a = new Algorithms();
        ImpImage thumb = new ImpImage();
        //Create Thumbnail
        thumb.setImg(a.shrinkImage(image.getImg(), 75, 75));
        //Create ImageIcon
        ImageIcon icon = new ImageIcon(thumb.getImg());
        //Create JButton
        JButton iconButton = new JButton(icon); 
        //Create ActionListener
        iconButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                bottomBarLabel.setText("Clicked");
                imagePanel.removeAll();
                imagePanel.add(images.get(position)); //Needs Fixing
                imagePanel.revalidate();
            }
        });
        //Add to previewPanel
        previewPanel.add(iconButton);
        previewPanel.revalidate();
        previewPanel.repaint();
    }
Run Code Online (Sandbox Code Playgroud)

我实现的方式是:1)打开图像,2)将图像添加到列表,3)创建图像的缩略图 -> 添加到 ImageIcon -> 添加到 Jbutton -> 添加到带有 actionListener 的组件。问题是我没有将按钮存储在列表中,因此它不知道其各自的图像在列表中的编号。

tom*_*416 5

您如何扩展 JButton 类。

class MyButton extends JButton{
    public int index;
    MyButton(){super();}
    MyButton(int index){super();this.index=index;}
}
Run Code Online (Sandbox Code Playgroud)

当需要获取索引时,将其投回MyButton并获取索引;

MyButton mybtn = (MyButton)this;
Run Code Online (Sandbox Code Playgroud)