我无法借用keyTyped方法的if检查。代码的后续部分是:
这里我初始化了Combobox:
private void initComponents()
{
this.cboDayModel = new DefaultComboBoxModel<ListItem>();
this.cboDay = new JComboBox<ListItem>( this.cboDayModel );
this.cboDay.addItemListener( this );
this.cboDay.setName( "cboDay" );
this.cboDay.setBackground( this.einAusClass.hPHB.btnColor );
this.cboDay.setEditable( true );
this.cboDay.getEditor().getEditorComponent().addKeyListener( this );
this.cboDay.getEditor().getEditorComponent().addFocusListener( this );
this.add( this.cboDay );
}
此时我检查输入的内容:
@Override
public void keyTyped( KeyEvent e )
{
if ( !( Character.isDigit( e.getKeyChar() ) ) )
{
e.consume();
return;
}
if ( e.getSource() instanceof JComboBox ) // <-------*************
{
System.out.println( "zz2" );
this.cbo = (JComboBox<ListItem>) e.getSource();
String str = ( (JTextField) cbo.getEditor().
getEditorComponent() ).getText();
int zahl = Integer.parseInt( "0" + str );
System.out.println( str + "" + zahl );
if ( this.cbo == cboDay )
{
if ( zahl < 1 || zahl > 31 )
{
e.consume();
return;
}
}
}
}
在keyTyped方法中,我检查
if ( e.getSource() instanceof JComboBox )
为什么它不会进入if if语句?
答案 0 :(得分:0)
e.getSource()
根据https://docs.oracle.com/javase/7/docs/api/java/util/EventObject.html没有返回object
JComboBox
这是getSource()的方法声明;
public Object getSource()
这将返回object
最初发生的Event
,因此您应该实际投射
e.getSource
对象为jcombobox
ex:
if(cboDay == (jcombobox)e.getSource())
您可以使用actioncommand
例如
cboDay.setActionCommand("combo");
public void keyTyped( KeyEvent e )
String action = e.getActionCommand();
if (action.equals("combo")) {
System.out.println("done!");
}
}