How to select all text in JTable cell when editing

后端 未结 3 1611
遇见更好的自我
遇见更好的自我 2021-01-02 02:12

I would like to have the editor in my editable JTables select all text in the cell when starting to edit. I have tried a couple of things that all revolve around calling JT

相关标签:
3条回答
  • 2021-01-02 02:32

    JTables can have many different components in a cell. It is usually a JTextField when you are editing. You need to firstly get the field and then select. You can get the length of the text by working through your modal. This code should get you started, you may want to place it within a List selection handler. ie.

     ListSelectionModel rowSM = this.getSelectionModel();
     rowSM.addListSelectionListener(new ListSelectionListener() {
        public void valueChanged(ListSelectionEvent e){
           DefaultCellEditor ed = (DefaultCellEditor)this.getCellEditor();
           JTextField jf = (JTextField)ed.getComponent();
           jf.select(0, *text.length()*);
           jf.requestFocusInWindow();
        }
     });
    

    Notably you will need to find the text.length(). Possibly something such as:

    this.getModel().getValueAt(this.getSelectedRow(), this.getSelectedColumn()).length();
    

    Disclaimer I haven't tested this code.

    0 讨论(0)
  • 2021-01-02 02:38

    The Table Select All Editor should work for you. It is the preferred solution so you don't have to keep creating custom editors. That is the columns containing integers should only accept integers. With you current code

    Your code does work partially. If you start editing using the F2 key, then the text is selected. However, when you use the mouse and double click on the cell then the second mouse event is passed to the editor so the caret can be positioned where you clicked and this removes the selection. A solution for this is:

    final JTextComponent jtc = (JTextComponent)c;
    jtc.requestFocus();
    //jtc.selectAll();
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            jtc.selectAll();
        }
    });
    
    0 讨论(0)
  • 2021-01-02 02:40
    public class SelectAllCellEditor extends DefaultCellEditor
    {
        public SelectAllCellEditor(final JTextField textField ) {
            super( textField );
            textField.addFocusListener( new FocusAdapter()
            {
                public void focusGained( final FocusEvent e )
                {
                    textField.selectAll();
                }
            } );
        }
    }
    
    0 讨论(0)
提交回复
热议问题