JTable中的JFileChooser

时间:2013-03-26 18:06:24

标签: java swing jtable jfilechooser tablecelleditor

我正在尝试创建一个新的组件进入JTable。它由一个JTextfield组成,当点击它时会产生一个JFileChooser,这样用户就可以浏览文件系统并选择想要的文件,然后用该文件的路径填充该字段。到目前为止,我已经达到了可以在编辑器中填充文本字段的程度,但是当我单击它时,FilecChooser不会产生。任何人都知道我在这里做错了什么?

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

    }

}

}

3 个答案:

答案 0 :(得分: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());

答案 1 :(得分: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();
            }
        });
    }
}

答案 2 :(得分: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);
    }
}