JTable Input Verifier

前端 未结 3 541
一整个雨季
一整个雨季 2021-02-09 18:18

I am trying to create a simple Input Verifier for a JTable. I ended up with overriding the method: editingStopped(). The problem is that the event does not include informations

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-09 18:51

    What worked for me (tip 'o the hat to kleopatra):

    private class CellEditor extends DefaultCellEditor {
    
        InputVerifier verifier = null;
    
        public CellEditor(InputVerifier verifier) {
            super(new JTextField());
            this.verifier = verifier;
    
        }
    
        @Override
        public boolean stopCellEditing() {
            return verifier.verify(editorComponent) && super.stopCellEditing();
        }
    
    }
    
    // ...
    
    private class PortVerifier extends InputVerifier {
    
        @Override
        public boolean verify(JComponent input) {
            boolean verified = false;
            String text = ((JTextField) input).getText();
            try {
                int port = Integer.valueOf(text);
                if ((0 < port) && (port <= 65535)) {
                    input.setBackground(Color.WHITE);
                    verified = true;
                } else {
                    input.setBackground(Color.RED);
                }
            } catch (NumberFormatException e) {
                input.setBackground(Color.RED);
            }
            return verified;
        }
    }
    
    // ...
    
    table.getColumn("Port").setCellEditor(new CellEditor(new PortVerifier()));
    

提交回复
热议问题