Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
411 views
in Technique[技术] by (71.8m points)

java - Is there a way to store data in a JButton?

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

The issue I am having is that I cannot get the image to change to the thumbnail that is selected as they are not linked to the images in the list. Is there a way I can store the index number of the image in the button, so when I click it I know which image to show in the List? Or is there another more intelligent way? Thanks.

 //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();
    }

The way I have implemented this is: 1) Open image, 2) Add image to List, 3)Create a thumbnail of image -> add to ImageIcon -> add to Jbutton -> add to component w/ actionListener. The issue is I don't store the buttons in a list so it doesn't know what number its respective image is in the List.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...