JTable防止字符串

时间:2017-07-01 22:55:53

标签: java numbers jtable

如何阻止JTable中的字符串并仅允许和显示数字?

例如我在键盘上按“a”我甚至不会在JTable单元格中显示“a”。除非用户输入数字,否则不会发生任何事情。那么如何防止甚至不显示“a”?

1 个答案:

答案 0 :(得分:0)

前段时间我遇到了类似的问题,并通过使用KeyListener进行验证来解决。这是一种肮脏的方式,但它的工作原理。唯一的缺点是,如果你是一个快速作家,你是否会尝试快速编辑很多单元格。无论如何,这里的代码对我有用。我添加了一些评论,但简而言之;如果给定的键是我们在TextField中允许的键,我们将覆盖正常的验证并使用TextField KeyListener进行检查。如果我们允许键,我们启用TextField编辑,如果没有,我们将其关闭以防止字符在TextField中打印。我希望这会对你有所帮助。

更新1: 在TestField上添加celleditor以防止过早插入数据。

public class TableValidation extends JFrame
{
public static void main(String args[])
{
    TableValidation x = new TableValidation();
    x.setVisible(true);
}

JPanel topPanel;
JTable table = new JTable();
JScrollPane scrollPane;
String[] columnNames;
String[][] dataValues;

public TableValidation()
{
    this.setTitle("JTable Cell Validation");
    this.setDefaultCloseOperation (EXIT_ON_CLOSE);
    this.setSize(300,112);

    // make our panel to tin the table to
    topPanel    = new JPanel();
    topPanel.setLayout(new BorderLayout());
    this.getContentPane().add(topPanel);

    // set some initial data for the table
    columnNames = new String[] {"Anything" ,"Numbers only"};
    dataValues  = new String[][] { {"h4x0r","1337"} };


    table.setRowHeight(50);
    table.setModel( new CustomTableModel(dataValues, columnNames) );

    TableColumn tableColumn = table.getColumnModel().getColumn(1); // apply our validation to the 2nd column
    JTextField textfield = new JTextField(); // the textbox to which we test our validation

    // setup our validation system. were passing the textfield as out celleditor source
    tableColumn.setCellEditor(new MyCellEditor(textfield));
    table.setCellSelectionEnabled(true);
    scrollPane = new JScrollPane(table);
    topPanel.add(scrollPane,BorderLayout.CENTER);
    textfield.addKeyListener(new KeyAdapter()
    {
        public void keyTyped(KeyEvent e)
        {
            // check what keys can pass our test
            if (textfield.isFocusOwner())
            if (e.getKeyChar() != KeyEvent.VK_BACK_SPACE) // we allow backspace, obviously
            if (!Character.isDigit(e.getKeyChar())) // if key is not a digit.. cancel editing
            {
                // when it detects an invalid input, set editable to false. this prevents the input to register
                textfield.setEditable(false);
                textfield.setBackground(Color.WHITE);
                return;
            }
            textfield.setEditable(true);
        }
    });
}
}
class MyCellEditor extends AbstractCellEditor implements TableCellEditor 
{
private static final long serialVersionUID = 1L;
private JTextField textField;

public MyCellEditor(JTextField textField)
{
    this.textField=textField;
}

@Override
public boolean isCellEditable(EventObject e) 
{
    if (super.isCellEditable(e)) {
        if (e instanceof MouseEvent) {
            MouseEvent me = (MouseEvent) e;
            return me.getClickCount() >= 2;
        }
        if (e instanceof KeyEvent) {
            KeyEvent ke = (KeyEvent) e;
            return ke.getKeyCode() == KeyEvent.VK_F2;
        }
    }
    return false;
}

@Override
public Object getCellEditorValue() 
{
    return this.textField.getText();
}

@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) 
{
    this.textField.setFont(table.getFont());
    this.textField.setText(value.toString());
    return this.textField;
}
}
class CustomTableModel extends DefaultTableModel
{
CustomTableModel(String[][] data,String[] names)
{
    super(data, names);
}

// we always pass true in our tablemodel so we can validate somewhere else
public boolean isCellEditable(int row,int cols)
{
    return true;
}
}