2 Replies Latest reply: Jan 22, 2014 3:49 AM by guyerlich RSS

    jtable - partial text selection

    guyerlich

      Hey all,

       

      I have a read-only table.

      Currently, when a user clicks on a cell, the whole cell is selected.

      I want to allow the user to select only a partial text in the cell - mainly for copy purposes.

      How can I achieve that?

        • 1. Re: jtable - partial text selection
          TPD-Opitz

          The trick (with Swing) is that the JTable must be enabled and you must register a custom Tableeditor that prevents the string from changing:

           

          public class SelectableTextTableTest {
              public static void main(String[] args) {
                  DefaultTableModel notEditableModel = new DefaultTableModel(11, 5) {
                      @Override
                      public Object getValueAt(int row, int column) {
                          return "Column " + column + " / Row " + row;
                      }
          
                      @Override
                      public boolean isCellEditable(int row, int column) {
                          return false;
                      }
                  };
          
                  JTable table = new JTable(notEditableModel) {
          
                      @Override
                      public boolean isCellEditable(int row, int column) {
                          return true;
                      }
                  };
          
                  JTextField textField = new JTextField();
                  textField.setEditable(false);
                  table.setDefaultEditor(Object.class, new DefaultCellEditor(textField));
                  JOptionPane.showMessageDialog(null, table);
              }
          }
          

           

          bye

          TPD

          • 2. Re: jtable - partial text selection
            guyerlich

            Great. Thanks