我的 JTable 有一个密码字段编辑器。如果用户单击编辑另一个字段时文本长度小于 8 位,我想显示一条错误消息。我试过焦点听众。但它不起作用。请帮助我,因为我刚刚开始使用 java swing。
class PasswordEditor extends DefaultCellEditor
{
TextBox m_passWord = new TextBox();
public PasswordEditor() {
super(new TextBox());
}
@Override
public Object getCellEditorValue() {
return this.m_passWord.getText();
}
@Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int column) {
Object fieldValue = value;
if(null == fieldValue)
fieldValue = Constants.EMPTY_STRING;
this.m_passWord.addInputMethodListener(new InputMethodListener() {
@Override
public void inputMethodTextChanged(InputMethodEvent event)
{
// TODO Auto-generated method stub
}
@Override
public void caretPositionChanged(InputMethodEvent event)
{
// TODO Auto-generated method stub
}
})
this.m_passWord.addFocusListener(new FocusListener() {
@Override
public void focusLost(FocusEvent e)
{
if (!e.isTemporary()) {
String content = PasswordEditor.this.m_passWord.getText();
System.out.println((content));
}
}
@Override
public void focusGained(FocusEvent e)
{
//TODO init
}
});
this.m_passWord.setEditable(true);
this.m_passWord.setText(fieldValue.toString());
return this.m_passWord;
}
}
最佳答案
据我了解,这个问题是关于验证编辑器中的输入(保护自身免受无效值影响的模型是另一回事,IMO)并在 s/时通知用户他/她的错误他尝试提交输入。
一个简单的方法是使用 InputVerifier:
- 在其验证方法中实现验证规则
- 在它的 shouldYieldFocus 中实现通知
- 继承 DefaultCellEditor 并覆盖其 stopCellEditing 以调用 shouldYieldFocus 并返回其结果(又名:拒绝提交编辑)
一些代码片段:
final InputVerifier iv = new InputVerifier() {
@Override
public boolean verify(JComponent input) {
JTextField field = (JTextField) input;
return field.getText().length() > 8;
}
@Override
public boolean shouldYieldFocus(JComponent input) {
boolean valid = verify(input);
if (!valid) {
JOptionPane.showMessageDialog(null, "invalid");
}
return valid;
}
};
DefaultCellEditor editor = new DefaultCellEditor(new JTextField()) {
{
getComponent().setInputVerifier(iv);
}
@Override
public boolean stopCellEditing() {
if (!iv.shouldYieldFocus(getComponent())) return false;
return super.stopCellEditing();
}
@Override
public JTextField getComponent() {
return (JTextField) super.getComponent();
}
};
JTable table = new JTable(10, 2);
table.setDefaultEditor(Object.class, editor);
关于java - 使用编辑器验证表格的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13508851/