I am using interactive JTable based on the code here.
What I need is that after double-click to edit the cell,
If right mouse click, it opens file chooser to select the file
else just enter the path manually after double clicking for all cells in the first column.
I added
TableColumn waweletFileColumn = table.getColumnModel().getColumn(InteractiveTableModel.TITLE_INDEX );
waweletFileColumn.setCellEditor(new FileChooserCellEditor());
in the interactive table to modify the cells' behavior.
public class FileChooserCellEditor extends DefaultCellEditor implements TableCellEditor {
/** Editor component */
private JTextField tf;
/** Selected file */
private String file = "";
private String type;
/**
* Constructor.
*/
public FileChooserCellEditor(String type) {
super(new JTextField());
this.type = type;
// Using a JButton as the editor component
tf = new JTextField();
tf.setBorder(null);
}
@Override
public Object getCellEditorValue() {
return file;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
file = myFileChooser(type);
fireEditingStopped();
tf.setText(file);
return tf;
}
public static String myFileChooser() {
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory( new File(System.getProperty("user.home"));
chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES );
chooser.setDialogTitle("Choose" );
chooser.setAcceptAllFileFilterUsed(true);
chooser.setDialogType(JFileChooser.OPEN_DIALOG);
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
direct = chooser.getSelectedFile();
return chooser.getSelectedFile().toString();
}
return "";
}
}
But how can I modify the code to open the file chooser if the right mouse click is clicked and act like a normal text field otherwise?
But how can I modify the code to open the file chooser if the right mouse click is clicked and act like a normal text field otherwise?
Get rid of the custom cell editor.
Instead you just use the default editor but you need to add a MouseListener to the text field of the editor to handle the right click and show the JFileChooser.
So the basic logic might be something like:
JTextField editField = new JTextField()
editfield.addMouseListener(...);
DefaultCellEditor editor = new DefaultCellEditor( editField );
table.getColumnModel().getColumn(???).setCellEditor(editor);
Then add your logic to the MouseListener
to display the JFileChooser
. When the file chooser is closed you get the selected file and update the text field. Something like:
JTextField textField = (JTextField)e.getSource();
JFileChooser fc = new JFileChooser(...);
int returnVal = fc.showOpenDialog(textField);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = fc.getSelectedFile();
textField.setText( file.toString() );
}