Java swing - displaying multiple images dynamically on JPanel

纵饮孤独 提交于 2019-12-10 00:16:37

问题


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


来源:https://stackoverflow.com/questions/8500746/java-swing-displaying-multiple-images-dynamically-on-jpanel

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