简体   繁体   English

使用变量作为文件路径将ImageIcon添加到JPanel

[英]Adding an ImageIcon to a JPanel using a variable as the file path

I have a csv file containing the file names of all my images. 我有一个包含所有图像文件名的csv文件。 I want to extract the file names from that file and use them to add the corresponding image to my GUI. 我想从该文件中提取文件名,并使用它们将相应的图像添加到我的GUI中。 I have a lot of images so I can't just type out all the file paths. 我有很多图像,所以我不能只输入所有文件路径。

It works if I use 如果我使用它就可以

img = new ImageIcon("resources/imagename.jpg");

but not if I use 但是如果我使用

String fileName = "resources/" + fileNameExtractedFromCSVFile;
img = new ImageIcon(fileName);

It's extracting the file name just fine, it just won't use it to locate the image. 它提取的文件名很好,只是不会用它来定位图像。 I would appreciate any help. 我将不胜感激任何帮助。

inspect the value of fileNameExtractedFromCSVFile before using it. 在使用前检查fileNameExtractedFromCSVFile的值。 seems like its not getting populated properly. 好像没有正确填充它。 If you are using an IDE, try to run the code in DEBUG mode and put a break point on this line to see what the value of the variables are. 如果使用的是IDE,请尝试以DEBUG模式运行代码,并在此行上放置一个断点,以查看变量的值。

If I did understood you correctly you need something like this please see the demo below and the code for it. 如果我确实正确地理解了您的需要,请参阅下面的演示及其代码。 In addition please created images package in your application. 另外,请在您的应用程序中创建图像包。

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

add this method to your class to read csv 将此方法添加到您的类中以读取csv

   public void csvread() throws IOException 
    {
        File file = new File("filenames.csv");
    List<String> lines = Files.readAllLines(file.toPath(), 
            StandardCharsets.UTF_8);
    for (String line : lines) {
        String[] array = line.split(",");
        jTextArea1.append(array[0]+"\n");
    }

    }

button csv read action 按钮csv读取动作

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { 私人void jButton1ActionPerformed(java.awt.event.ActionEvent evt){

    try {
        csvread();
    } catch (IOException ex) {
        Logger.getLogger(ImageDisplay.class.getName()).log(Level.SEVERE, null, ex);
    }


} 

text area mouse released get selected text and display image on jlabel 释放文本区域鼠标可获取选定的文本并在jlabel上显示图像

private void jTextArea1MouseReleased(java.awt.event.MouseEvent evt) {                                         

    if (jTextArea1.getSelectedText() != null) {

        String s = jTextArea1.getSelectedText();

        ImageIcon imageselect = new ImageIcon(getClass().getResource("/images/" + s));
        jLabel2.setIcon(imageselect);

    } else {
        jLabel4.setVisible(true);
    }

}  

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

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