【问题标题】:How to open file chooser in the interactive Jtable with right mouse click如何在交互式 Jtable 中单击鼠标右键打开文件选择器
【发布时间】:2018-09-26 22:22:52
【问题描述】:

我正在使用基于代码here的交互式JTable。

我需要的是双击编辑单元格后,
如果单击鼠标右键,它会打开文件选择器以选择文件
否则只需双击第一列中的所有单元格后手动输入路径。

我加了

TableColumn waweletFileColumn = table.getColumnModel().getColumn(InteractiveTableModel.TITLE_INDEX );
    waweletFileColumn.setCellEditor(new FileChooserCellEditor());

在交互式表格中修改单元格的行为。

    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 "";

        }
}

但是如果单击鼠标右键,我如何修改代码以打开文件选择器,否则就像普通文本字段一样?

【问题讨论】:

    标签: java swing jtable jfilechooser mouse-listeners


    【解决方案1】:

    但是如果单击鼠标右键,我如何修改代码以打开文件选择器,否则就像普通文本字段一样?

    摆脱自定义单元格编辑器。

    您只需使用默认编辑器,但您需要在编辑器的文本字段中添加一个 MouseListener 来处理右键单击并显示 JFileChooser。

    所以基本逻辑可能是这样的:

    JTextField editField = new JTextField()
    editfield.addMouseListener(...);
    DefaultCellEditor editor = new DefaultCellEditor( editField );
    table.getColumnModel().getColumn(???).setCellEditor(editor);
    

    然后将您的逻辑添加到MouseListener 以显示JFileChooser。当文件选择器关闭时,您将获得所选文件并更新文本字段。比如:

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

    【讨论】:

    • 谢谢它的工作,看起来我的解决方案过于复杂了:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-07-25
    • 1970-01-01
    • 2012-08-18
    • 1970-01-01
    • 2021-03-31
    • 1970-01-01
    • 2011-05-30
    相关资源
    最近更新 更多