简体   繁体   English

Java Swing-在JPanel上动态显示多个图像

[英]Java swing - displaying multiple images dynamically on JPanel

I have searched many places to add and display images dynamically on JPanel but couldn't get proper help. 我已经搜索了许多地方,可以在JPanel上动态添加和显示图像,但无法获得适当的帮助。 Basically I have JPanel on which I have to display many images vertically but it should be dynamic. 基本上,我有JPanel,必须在其上垂直显示许多图像,但它应该是动态的。

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 macthedImages是bufferedImages的数组searchResultPanel是JPanel

1) you have to set proper LayoutManager , 1)您必须设置适当的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 2)对于JLabel中的许多图像, GridLayout最好是选项,以防您要在一个JPanel上查看所有图像

3) use CardLayout , if you want to see each Image separatelly 3)如果要单独查看每个图像,请使用CardLayout

4) maybe there no needed re-create 4)也许没有必要重新创建

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

only to set 只设置

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

5) maybe put JPanel to the JSCrollPane 5)可能将JPanel放入JSCrollPane

6) if you add/remove JCOmponents on Runtime you have to call 6)如果在运行时添加/删除JCOmponent,则必须调用

revalidate();
repaint()// sometimes required

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,但必须考虑网格布局的行和列。

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

Or if you want to show one image at a time then use CardLayout. 或者,如果您想一次显示一张图像,请使用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 它提供了许多方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM