Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Java FileChooserCellEditor
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.filechooser.FileNameExtensionFilter;
import javax.swing.table.TableCellEditor;
public class FileChooserCellEditor extends DefaultCellEditor implements TableCellEditor {
private static final int CLICK_COUNT_TO_START = 2;
private JButton button;
private JFileChooser fileChooser;
private String selectedFile = "";
public FileChooserCellEditor(FileNameExtensionFilter filter) {
super(new JTextField());
setClickCountToStart(CLICK_COUNT_TO_START);
button = new JButton();
button.setBackground(Color.white);
button.setFont(button.getFont().deriveFont(Font.PLAIN));
button.setBorder(null);
fileChooser = new JFileChooser();
fileChooser.setFileFilter(filter);
}
@Override
public Object getCellEditorValue() {
return selectedFile;
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (value != null) {
selectedFile = value.toString();
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
fileChooser.setSelectedFile(new File(selectedFile));
if (fileChooser.showOpenDialog(button) == JFileChooser.APPROVE_OPTION) {
selectedFile = fileChooser.getSelectedFile().getAbsolutePath();
}
fireEditingStopped();
}
});
button.setText(selectedFile);
return button;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.