Java swing - displaying multiple images dynamicall

2019-04-17 08:01发布

问题:

I have searched many places to add and display images dynamically on JPanel but couldn't get proper help. Basically I have JPanel on which I have to display many images vertically but it should be dynamic.

for(int i=0;i<macthedImages.length;i++) {
    JLabel jLabel = new JLabel(new ImageIcon(macthedImages[i]));
    searchResultPanel.add(jLabel);
}

macthedImages is an array of bufferedImages searchResultPanel is JPanel

回答1:

If you want to show all images at same time then use GridLayout but you have to consider rows and columns of grid layout.

GridLayout gl = new gridLayout(2,macthedImages.length/2);

Or if you want to show one image at a time then use CardLayout. Like this:

CardLayout cl = new CardLayout();
for(int i=0;i<macthedImages.length;i++){
        JLabel jLabel = new JLabel(new ImageIcon(macthedImages[i]));
        cl.add(jLabel, "jLabel"+i);
    }

In second option you can show any image by firing event. It provides many methods



回答2:

1) you have to set proper LayoutManager,

2) for lots of Images in the JLabel would be GridLayout best options, in case that you want to see all images on one JPanel

3) use CardLayout, if you want to see each Image separatelly

4) maybe there no needed re-create

JLabel jLabel = new JLabel(new ImageIcon(macthedImages[i]));

only to set

jLabel[i].setIcon(macthedImages[i]);

5) maybe put JPanel to the JSCrollPane

6) if you add/remove JCOmponents on Runtime you have to call

revalidate();
repaint()// sometimes required