2015-04-19 2 views
0

Я хочу, чтобы добавить фотографию из выбранного файла образом на JPanel, но, следующий код не похож на работу:Как установить ImageIcon JLabel от absolutePath экземпляра File пути

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(); 
    } 
} 

Какую часть я пропускаю ? Спасибо вам за вашу помощь.

[EDIT]

Это класс, где реализован этот код:

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

Что является ОС вашей системы, и вы можете опубликовать вывод 'getImageURL()' – Blip

+0

Почему бы просто не использовать ImageIcon (File)? – MadProgrammer

+0

@MadProgrammer Вы имеете в виду в этом контексте 'new ImageIcon (fileBeingOpened)'? – Blip

ответ

0

я «думаю» проблема с использованием GroupLayout, это вообще боль в ... Код ... Лично я бы использовать другую раскладку, даже с формой редактора и добавить метку держателя места для фота, который вы можете использовать, чтобы установить значок - MadProgrammer вчера

Я изменил макет панели в в макет карты, и теперь это хорошо, спасибо всем :)

0

Документация ImageIcon(String filename) гласит, что:

Создает ImageIcon из указанного файла. Изображение будет предварительно загружено с помощью MediaTracker для контроля состояния загрузки изображения. Указанная строка может быть именем файла или файлом. При указании пути используйте разделитель ("/") интернет-стандарта в качестве разделителя. (Строка преобразуется в URL-адрес, поэтому функция прямой косой черты работает во всех системах.) Например, укажите: new ImageIcon("images/myImage.gif") Описание инициализируется в строке имени файла.

Так, что я думаю, что ваша проблема с путем, который вы дали в качестве параметров, который имеет \ в пути.

+0

Я заменил строку 'Icon icon = new ImageIcon (getImageURL());' с символом Icon icon = new ImageIcon (getImageURL(). Replace ("\ \ ","/"));' и он по-прежнему не работает:/ – Logos

+0

"/" или "\" разделители путей под окнами не имеют значения, api будет настраиваться автоматически, они имеют значение только в системах * nix – MadProgrammer

Смежные вопросы