2013-03-26 33 views
0

所有我試圖創建一個新的組件去一個JTable。它由一個JTextfield組成,當它被點擊時產生一個JFileChooser,這樣用戶就可以瀏覽文件系統並選擇需要的文件,然後用該文件的路徑填充該字段。到目前爲止,我已經到了可以在編輯器中填充文本字段的地步,但是當我單擊它時,FilecChooser不會產生。任何人都知道我在這裏做錯了什麼?JTable中的JFileChooser

public class FileBrowserCellEditor extends AbstractCellEditor implements TableCellEditor, ActionListener { 

private static final long serialVersionUID = 1L; 
private Component frame; 
JButton button; 
JTextField textField; 
String path; 
JFileChooser fc; 
protected static final String EDIT = "edit"; 

public FileBrowserCellEditor(Component frame){ 
    this.frame = frame; 

    textField = new JTextField(); 
    textField.setActionCommand(EDIT); 
    textField.addActionListener(this); 

    fc = new JFileChooser(); 
} 

@Override 
public Object getCellEditorValue() { 

    return path; 

} 

@Override 
public Component getTableCellEditorComponent(JTable arg0, Object arg1, 
     boolean arg2, int arg3, int arg4) { 

    return textField; 
} 

@Override 
public void actionPerformed(ActionEvent e) { 

    //Debug 
    System.out.println(e.getActionCommand()); 

    if (EDIT.equals(e.getActionCommand())) { 
     //The user has clicked the cell, so 
     //bring up the dialog. 
     textField.setText(path); 
     fc.showOpenDialog(frame); 

     fireEditingStopped(); //Make the renderer reappear. 

    } else { //User pressed dialog's "OK" button. 
     //currentColor = colorChooser.getColor(); 

      File file = fc.getSelectedFile(); 
      this.path = file.getAbsolutePath(); 

    } 

} 

} 
+1

請嘗試將它作爲'MouseListener'而不是'ActionListener'。 – Brian 2013-03-26 18:08:22

回答

1

enter image description here
你可以試試下面的代碼:

import javax.swing.*; 
import javax.swing.border.*; 
import java.awt.*; 
import java.awt.event.*; 
import javax.swing.table.*; 
import java.io.*; 

class TableFileChooser extends JFrame 
{ 
    private JTable table; 
    private JScrollPane jsPane; 
    private TableModel myModel; 
    private JPanel dialogPanel; 
    private JTextField tf[]; 
    private JLabel  lbl[]; 
    public void prepareAndShowGUI() 
    { 
     setTitle("FileChooser in JTable"); 
     myModel = new MyModel(); 
     table = new JTable(myModel); 
     jsPane = new JScrollPane(table); 
     table.addMouseListener(new MyMouseAdapter()); 
     getContentPane().add(jsPane); 
     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     prepareDialogPanel(); 
     pack(); 
     setLocationRelativeTo(null); 
     setVisible(true); 

    } 
    private void prepareDialogPanel() 
    { 
     dialogPanel = new JPanel(); 
     int col = table.getColumnCount() - 1; 
     dialogPanel.setLayout(new GridLayout(col,2)); 
     tf = new JTextField[col]; 
     lbl = new JLabel[col]; 
     for (int i = 0; i < col; i++) 
     { 
      lbl[i] = new JLabel(table.getColumnName(i)); 
      tf[i] = new JTextField(10); 
      dialogPanel.add(lbl[i]); 
      dialogPanel.add(tf[i]); 
     } 
    } 
    private void populateTextField(String[] s) 
    { 
     for (int i = 0 ; i < s.length ; i++) 
     { 
      tf[i].setText(s[i]); 
     } 
    } 

    private class MyMouseAdapter extends MouseAdapter 
    { 
     @Override 
     public void mousePressed(MouseEvent evt) 
     { 
      int x = evt.getX(); 
      int y = evt.getY(); 
      int row = table.rowAtPoint(new Point(x,y)); 
      int col = table.columnAtPoint(new Point(x,y)); 
      if (col == 2) 
      { 
       String value = load(); 
       if (value!=null && ! "null".equalsIgnoreCase(value.trim()) && ! "".equalsIgnoreCase(value.trim())) 
       { 
        myModel.setValueAt(value,row,col); 
       } 
       else 
       { 
        myModel.setValueAt("ChooseFile",row,col); 
       } 
      } 
     } 
    } 
    //Loads the file 
    private String load() 
    { 
     JFileChooser chooser = new JFileChooser("."); 
     chooser.setDialogTitle("Open"); 
     chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); 
     int returnVal = chooser.showOpenDialog(this); 
     if(returnVal == JFileChooser.APPROVE_OPTION) 
     { 
      File file = chooser.getSelectedFile(); 
      if (file!= null) 
      { 
       return file.getAbsolutePath(); 
      } 
      else 
      { 
       JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE); 
       return null; 
      } 
     } 
     return null; 
    } 
    private class MyModel extends AbstractTableModel 
    { 
     String[] columns = { 
          "Roll No.", 
          "Name", 
          "File Name" 
          }; 
     String[][] inData = { 
           {"1","Anthony Hopkins","ChooseFile"}, 
           {"2","James William","ChooseFile"}, 
           {"3","Mc. Donald","ChooseFile"} 
          }; 
     @Override 
     public void setValueAt(Object value, int row, int col) 
     { 
      inData[row][col] = (String)value; 
      fireTableCellUpdated(row,col); 
     } 
     @Override 
     public Object getValueAt(int row, int col) 
     { 
      return inData[row][col]; 
     } 
     @Override 
     public int getColumnCount() 
     { 
      return columns.length; 
     } 
     @Override 
     public int getRowCount() 
     { 
      return inData.length; 
     } 
     @Override 
     public String getColumnName(int col) 
     { 
      return columns[col]; 
     } 
     @Override 
     public boolean isCellEditable(int row ,int col) 
     { 
      return false; 
     } 
    } 
    public static void main(String st[]) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       TableFileChooser td = new TableFileChooser(); 
       td.prepareAndShowGUI(); 
      } 
     }); 
    } 
} 
+0

雖然這個工作,我希望實現一個解決方案使用AbstractCellEditor類,而不是訴諸使用像這樣的方法。 – 2013-03-26 18:29:29

+0

@ChrisManess:你想'JTextField'作爲單元格編輯器? – 2013-03-26 18:33:12

1

這裏是顯示當您編輯單元格的自定義對話框的例子。您應該能夠定製它使用一個JFileChooser而不是自定義對話框:

import java.awt.*; 
import java.awt.event.*; 
import javax.swing.*; 
import javax.swing.table.*; 

/* 
* The editor button that brings up the dialog. 
*/ 
//public class TablePopupEditor extends AbstractCellEditor 
public class TablePopupEditor extends DefaultCellEditor 
    implements TableCellEditor 
{ 
    private PopupDialog popup; 
    private String currentText = ""; 
    private JButton editorComponent; 

    public TablePopupEditor() 
    { 
     super(new JTextField()); 

     setClickCountToStart(1); 

     // Use a JButton as the editor component 

     editorComponent = new JButton(); 
     editorComponent.setBackground(Color.white); 
     editorComponent.setBorderPainted(false); 
     editorComponent.setContentAreaFilled(false); 

     // Make sure focus goes back to the table when the dialog is closed 
     editorComponent.setFocusable(false); 

     // Set up the dialog where we do the actual editing 

     popup = new PopupDialog(); 
    } 

    public Object getCellEditorValue() 
    { 
     return currentText; 
    } 

    public Component getTableCellEditorComponent(
     JTable table, Object value, boolean isSelected, int row, int column) 
    { 

     SwingUtilities.invokeLater(new Runnable() 
     { 
      public void run() 
      { 
       System.out.println("run"); 
       popup.setText(currentText); 
//    popup.setLocationRelativeTo(editorComponent); 
       Point p = editorComponent.getLocationOnScreen(); 
       popup.setLocation(p.x, p.y + editorComponent.getSize().height); 
       popup.show(); 
       fireEditingStopped(); 
      } 
     }); 

     currentText = value.toString(); 
     editorComponent.setText(currentText); 
     return editorComponent; 
    } 

    /* 
    * Simple dialog containing the actual editing component 
    */ 
    class PopupDialog extends JDialog implements ActionListener 
    { 
     private JTextArea textArea; 

     public PopupDialog() 
     { 
      super((Frame)null, "Change Description", true); 

      textArea = new JTextArea(5, 20); 
      textArea.setLineWrap(true); 
      textArea.setWrapStyleWord(true); 
      KeyStroke keyStroke = KeyStroke.getKeyStroke("ENTER"); 
      textArea.getInputMap().put(keyStroke, "none"); 
      JScrollPane scrollPane = new JScrollPane(textArea); 
      getContentPane().add(scrollPane); 

      JButton cancel = new JButton("Cancel"); 
      cancel.addActionListener(this); 
      JButton ok = new JButton("Ok"); 
      ok.setPreferredSize(cancel.getPreferredSize()); 
      ok.addActionListener(this); 

      JPanel buttons = new JPanel(); 
      buttons.add(ok); 
      buttons.add(cancel); 
      getContentPane().add(buttons, BorderLayout.SOUTH); 
      pack(); 

      getRootPane().setDefaultButton(ok); 
     } 

     public void setText(String text) 
     { 
      textArea.setText(text); 
     } 

     /* 
     * Save the changed text before hiding the popup 
     */ 
     public void actionPerformed(ActionEvent e) 
     { 
      if ("Ok".equals(e.getActionCommand())) 
      { 
       currentText = textArea.getText(); 
      } 

      textArea.requestFocusInWindow(); 
      setVisible(false); 
     } 
    } 

    public static void main(String[] args) 
    { 
     String[] columnNames = {"Item", "Description"}; 
     Object[][] data = 
     { 
      {"Item 1", "Description of Item 1"}, 
      {"Item 2", "Description of Item 2"}, 
      {"Item 3", "Description of Item 3"} 
     }; 

     JTable table = new JTable(data, columnNames); 
     table.getColumnModel().getColumn(1).setPreferredWidth(300); 
     table.setPreferredScrollableViewportSize(table.getPreferredSize()); 
     JScrollPane scrollPane = new JScrollPane(table); 

     // Use the popup editor on the second column 

     TablePopupEditor popupEditor = new TablePopupEditor(); 
     table.getColumnModel().getColumn(1).setCellEditor(popupEditor); 

     JFrame frame = new JFrame("Popup Editor Test"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(new JTextField(), BorderLayout.NORTH); 
     frame.add(scrollPane); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 
} 
4

這裏是顯示一個JFileChooser當電池雙擊一個簡單的細胞編輯:

import java.awt.Color; 
import java.awt.Component; 
import java.awt.Font; 
import java.io.File; 
import javax.swing.DefaultCellEditor; 
import javax.swing.JButton; 
import javax.swing.JFileChooser; 
import javax.swing.JTable; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 
import javax.swing.table.TableCellEditor; 

public class FileChooserCellEditor extends DefaultCellEditor implements TableCellEditor { 

    /** Number of clicks to start editing */ 
    private static final int CLICK_COUNT_TO_START = 2; 
    /** Editor component */ 
    private JButton button; 
    /** File chooser */ 
    private JFileChooser fileChooser; 
    /** Selected file */ 
    private String file = ""; 

    /** 
    * Constructor. 
    */ 
    public FileChooserCellEditor() { 
     super(new JTextField()); 
     setClickCountToStart(CLICK_COUNT_TO_START); 

     // Using a JButton as the editor component 
     button = new JButton(); 
     button.setBackground(Color.white); 
     button.setFont(button.getFont().deriveFont(Font.PLAIN)); 
     button.setBorder(null); 

     // Dialog which will do the actual editing 
     fileChooser = new JFileChooser(); 
    } 

    @Override 
    public Object getCellEditorValue() { 
     return file; 
    } 

    @Override 
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { 
     file = value.toString(); 
     SwingUtilities.invokeLater(new Runnable() { 
      public void run() { 
       fileChooser.setSelectedFile(new File(file)); 
       if (fileChooser.showOpenDialog(button) == JFileChooser.APPROVE_OPTION) { 
        file = fileChooser.getSelectedFile().getAbsolutePath(); 
       } 
       fireEditingStopped(); 
      } 
     }); 
     button.setText(file); 
     return button; 
    } 
} 

要將它添加到您的JTable

yourJTable.getColumnModel().getColumn(yourColumnIndex).setCellEditor(new FileChooserCellEditor());