如何从文件实例的绝对路径设置 jLabel 的 ImageIcon

How to set jLabel's ImageIcon from File instance's absolutePath

我想将所选图像文件中的照片添加到 jPanel,但是以下代码似乎不起作用:

    private void browsePhotoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                  
    JFileChooser fileChooser = new JFileChooser();
    String[] fileSuffixes = ImageIO.getReaderFileSuffixes();
    for(String fileSuffix:fileSuffixes){
        FileFilter filter = new FileNameExtensionFilter(fileSuffix + " files", fileSuffix);
        fileChooser.addChoosableFileFilter(filter);
    }
    int selection = fileChooser.showOpenDialog(EmployeeInternalFrame.this);
    if(selection == JFileChooser.APPROVE_OPTION){
        File fileBeingOpened = fileChooser.getSelectedFile();
        setPhotoFile(fileBeingOpened);
        setImageURL(getPhotoFile().getAbsolutePath());
        photoPanel.removeAll();
        Icon icon = new ImageIcon(getImageURL());
        JLabel label = new JLabel(icon, SwingConstants.LEFT);
        photoPanel.add(label);
        photoPanel.repaint();
    }
}

我缺少哪一部分?感谢大家的帮助。

[编辑]

这是上面代码实现的 Class :

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package forms;

import dataobjects.Employee;
import datamodels.EmployeeTableModel;
import datacontrollers.EmployeeController;
import java.io.File;
import java.awt.Image;
import java.awt.Label;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.filechooser.FileFilter;
import javax.swing.SwingConstants;
import javax.swing.JFileChooser;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JLabel;
import javax.swing.Icon;
import javax.imageio.ImageIO;
import javax.swing.JOptionPane;

/**
 *
 * @author Benignus
 */
public class EmployeeInternalFrame extends javax.swing.JInternalFrame{

    private EmployeeTableModel employeeTableModel;
    private String imageURL;
    private EmployeeController employeeController;
    private File photoFile;
    private Image photoImage;

    /**
     * Creates new form EmployeeInternalFrame
     */
    public EmployeeInternalFrame() {
        initComponents();
        employeeTableModel = new EmployeeTableModel();
        employeeTable.setModel(employeeTableModel);
        employeeController = new EmployeeController(this);
        employeeTable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
            @Override
            public void valueChanged(ListSelectionEvent e) {
                int row = employeeTable.getSelectedRow();
                if(row != -1){
                    Employee employee = employeeTableModel.getAtIndex(row);
                    ssnText.setText(employee.getSsn());
                    nameText.setText(employee.getName());
                    positionComboBox.setSelectedItem(employee.getPosition());
                    basePayText.setText(String.valueOf(employee.getBasePay()));
                    banText.setText(employee.getBan());
                    imageURL = employee.getPhoto();
                }
            }
        });
        refreshTable();
    }


    public String getImageURL() {
        return imageURL;
    }

    public void setImageURL(String imageURL){
        this.imageURL = imageURL;
    }

    public EmployeeTableModel getEmployeeTableModel() {
        return employeeTableModel;
    }

    public JButton getBackButton() {
        return backButton;
    }

    public JTextField getBanText() {
        return banText;
    }

    public JTextField getBasePayText() {
        return basePayText;
    }

    public JButton getBrowsePhotoButton() {
        return browsePhotoButton;
    }

    public JTable getEmployeeTable() {
        return employeeTable;
    }

    public JButton getInputButton() {
        return inputButton;
    }

    public JTextField getNameText() {
        return nameText;
    }

    public JPanel getPhotoPanel() {
        return photoPanel;
    }

    public JComboBox getPositionComboBox() {
        return positionComboBox;
    }

    public JComboBox getSearchByComboBox() {
        return searchByComboBox;
    }

    public JTextField getSearchText() {
        return searchText;
    }

    public JTextField getSsnText() {
        return ssnText;
    }

    private void refreshTable(){
        employeeController.selectAll();
    }

    public File getPhotoFile() {
        return photoFile;
    }

    public void setPhotoFile(File photoFile) {
        this.photoFile = photoFile;
    }

    public Image getPhotoImage() {
        return photoImage;
    }

    public void setPhotoImage(Image photoImage) {
        this.photoImage = photoImage;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        photoPanel = new javax.swing.JPanel();
        browsePhotoButton = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        employeeTable = new javax.swing.JTable();
        positionComboBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        ssnText = new javax.swing.JTextField();
        nameText = new javax.swing.JTextField();
        inputButton = new javax.swing.JButton();
        backButton = new javax.swing.JButton();
        basePayText = new javax.swing.JTextField();
        banText = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        searchText = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        searchByComboBox = new javax.swing.JComboBox();

        photoPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        javax.swing.GroupLayout photoPanelLayout = new javax.swing.GroupLayout(photoPanel);
        photoPanel.setLayout(photoPanelLayout);
        photoPanelLayout.setHorizontalGroup(
            photoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 111, Short.MAX_VALUE)
        );
        photoPanelLayout.setVerticalGroup(
            photoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 149, Short.MAX_VALUE)
        );

        browsePhotoButton.setText("Browse Photo");
        browsePhotoButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                browsePhotoButtonActionPerformed(evt);
            }
        });

        employeeTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(employeeTable);

        positionComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel1.setText("SSN");

        jLabel2.setText("Name");

        jLabel3.setText("Position");

        jLabel4.setText("Base Pay");

        inputButton.setText("Input");
        inputButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                inputButtonActionPerformed(evt);
            }
        });

        backButton.setText("Back");

        jLabel5.setText("BAN");

        jLabel7.setText("Search By :");

        searchByComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jLabel5)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE)
                                        .addComponent(banText, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGroup(layout.createSequentialGroup()
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                    .addComponent(jLabel1)
                                                    .addComponent(jLabel2)
                                                    .addComponent(jLabel4))
                                                .addGap(6, 6, 6))
                                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                                .addComponent(jLabel3)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                            .addComponent(basePayText)
                                            .addComponent(ssnText, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                                            .addComponent(nameText, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                                            .addComponent(positionComboBox, 0, 170, Short.MAX_VALUE))))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(photoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(browsePhotoButton, javax.swing.GroupLayout.PREFERRED_SIZE, 110, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(inputButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(20, 20, 20)
                                .addComponent(backButton, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 470, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(5, 5, 5)
                        .addComponent(searchByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(10, 10, 10)
                        .addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(photoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(9, 9, 9)
                        .addComponent(browsePhotoButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(26, 26, 26)
                                .addComponent(jLabel2)
                                .addGap(63, 63, 63)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabel4)
                                    .addComponent(basePayText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(ssnText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(20, 20, 20)
                                .addComponent(nameText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(20, 20, 20)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(positionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel3))))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(banText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel5))
                        .addGap(17, 17, 17)))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(inputButton)
                    .addComponent(backButton))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel7)
                    .addComponent(searchByComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(15, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void browsePhotoButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                  
        JFileChooser fileChooser = new JFileChooser();
        String[] fileSuffixes = ImageIO.getReaderFileSuffixes();
        for(String fileSuffix:fileSuffixes){
            FileFilter filter = new FileNameExtensionFilter(fileSuffix + " files", fileSuffix);
            fileChooser.addChoosableFileFilter(filter);
        }
        int selection = fileChooser.showOpenDialog(EmployeeInternalFrame.this);
        if(selection == JFileChooser.APPROVE_OPTION){
            File fileBeingOpened = fileChooser.getSelectedFile();
            setPhotoFile(fileBeingOpened);
            setImageURL(getPhotoFile().getAbsolutePath());
            photoPanel.removeAll();
            Icon icon = new ImageIcon(getImageURL());
            JLabel label = new JLabel(icon, SwingConstants.LEFT);
            photoPanel.add(label);
            photoPanel.repaint();
            JOptionPane.showMessageDialog(this, getImageURL());
        }
    }                                                 

    private void inputButtonActionPerformed(java.awt.event.ActionEvent evt) {                                            
        if(inputButton.getText().equalsIgnoreCase("Input")){

        }
        else if(inputButton.getText().equalsIgnoreCase("Save")){

        }
        else if(inputButton.getText().equalsIgnoreCase("Update")){

        }
    }                                           

    // Variables declaration - do not modify                     
    private javax.swing.JButton backButton;
    private javax.swing.JTextField banText;
    private javax.swing.JTextField basePayText;
    private javax.swing.JButton browsePhotoButton;
    private javax.swing.JTable employeeTable;
    private javax.swing.JButton inputButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField nameText;
    private javax.swing.JPanel photoPanel;
    private javax.swing.JComboBox positionComboBox;
    private javax.swing.JComboBox searchByComboBox;
    private javax.swing.JTextField searchText;
    private javax.swing.JTextField ssnText;
    // End of variables declaration                   
}

ImageIcon(String filename) 的文档指出:

Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path. When specifying a path, use the Internet-standard forward-slash ("/") as a separator. (The string is converted to an URL, so the forward-slash works on all systems.) For example, specify: new ImageIcon("images/myImage.gif") The description is initialized to the filename string.

因此,我认为您的问题出在您作为参数给出的路径中,路径中包含 \

I "think" the problem is with the use of GroupLayout, it's generally a pain in the ... Code ... Personally, I'd use a different layout, even with the form editor and add a place holder label for the phot, which you can use to set the icon – MadProgrammer yesterday

我把panel的布局改成了Card Layout,现在好了,谢谢大家:)