如何从File实例的absolutePath设置jLabel的ImageIcon

时间:2015-04-19 07:43:05

标签: java swing file jpanel jlabel

我想将所选图像文件中的照片添加到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();
    }
}

我错过了哪一部分?感谢您的帮助。

[编辑]

这是实现上述代码的类:

/*
 * 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                   
}

2 个答案:

答案 0 :(得分:0)

ImageIcon(String filename)的文档指出:

  

从指定的文件创建ImageIcon。将使用MediaTracker预先加载图像以监控图像的加载状态。指定的String可以是文件名或文件路径。指定路径时,请使用Internet标准正斜杠(“/”)作为分隔符。 (该字符串将转换为URL,因此正斜杠适用于所有系统。)例如,指定:       new ImageIcon("images/myImage.gif")   描述初始化为文件名字符串。

所以,我认为您的问题在于您作为参数在路径中包含 \ 的路径。

答案 1 :(得分:0)

  

我&#34;思考&#34;问题在于使用GroupLayout,它通常是一个   代码......个人而言,我甚至使用不同的布局   使用表单编辑器并为phot添加占位符标签   你可以用来设置图标 - 昨天的MadProgrammer

我将面板的布局更改为卡布局,现在很好,谢谢大家:)