在Java中创建未定义数量的Jlabels

时间:2015-12-02 15:36:22

标签: java swing jlabel

我使用Java swing在Java中创建程序。我包括搜索功能,此搜索的结果保存在ArrayList字符串中。我需要显示这些结果,但作为搜索,不可能知道数组中保存的项目数量。那么如何创建和添加未知数量的Jlabels?

提前致谢。

2 个答案:

答案 0 :(得分:3)

你也可以弄清楚这一点,

// you already have this searched result's arraylist
ArralyList<String> allsearchresult = new ArrayList<String>();

JLabel ll = null;
for(String label : allsearchresult ){
   ll = new JLabel(label);
   frame.add(ll); // it's my idea, it can be change according you req.
   // set other necessary requirements...
}

答案 1 :(得分:2)

如上所述,为了方便和可选择性,在JList中显示您的图像。

例如:

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;

@SuppressWarnings("serial")
public class ImageList extends JPanel {
    private static final String BASE_PATH = "http://file.kelleybluebookimages.com/"
            + "kbb/images/content/editorial/";
    private static final String[] PATHS = {
        "2015-acura-tlx-guide-180.jpg",
        "13A420TFSI_01_hrgb-180.jpg",
        "CT_071713_BMW320i_0439-180.jpg",
        "2013-Cadillac-ATS-137-180.jpg",
        "EJ2V1342-180.jpg",
        "2014LexusIS005-180.jpg",
        "2014-volvo-s60-180.jpg",
        "2015-jeep-renegade-profile-180.jpg"
    };
    private DefaultListModel<Icon> listModel = new DefaultListModel<>();
    private JList<Icon> imageJList = new JList<>(listModel);

    public ImageList() throws IOException {
        for (String path : PATHS) {
            String imgPath = BASE_PATH + path;
            URL url = new URL(imgPath);
            BufferedImage img = ImageIO.read(url);
            listModel.addElement(new ImageIcon(img));
        }

        imageJList.setVisibleRowCount(4);
        JScrollPane scrollPane = new JScrollPane(imageJList);
        scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

        add(scrollPane);
    }    

    private static void createAndShowGui() {
        JFrame frame = new JFrame("ImageList");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        try {
            frame.getContentPane().add(new ImageList());
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(-1);
        }
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}