0

JTable 内に入る新しいコンポーネントを作成しようとしています。クリックすると JFileChooser が生成される JTextfield で構成されているため、ユーザーはファイル システムを参照して必要なファイルを選択し、そのファイルへのパスをフィールドに入力できます。これまでのところ、エディターでテキスト フィールドを入力できるところまで来ましたが、クリックしても 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();

    }

}

}
4

3 に答える 3

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);
    }
}
于 2013-03-26T18:41:34.483 に答える
1

ここに画像の説明を入力
次のコードを試すことができます。

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();
            }
        });
    }
}
于 2013-03-26T18:18:43.017 に答える