gpt4 book ai didi

java - 检查可编辑的 jcombobox

转载 作者:太空宇宙 更新时间:2023-11-04 12:33:55 25 4
gpt4 key购买 nike

我无法在 keyTyped 方法的 if 检查中借出。部分代码如下:

这里我初始化组合框:

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 语句内部?

最佳答案

根据 https://docs.oracle.com/javase/7/docs/api/java/util/EventObject.html

e.getSource() 不会返回 JComboBox对象这是 getSource() 的方法声明;public Object getSource() 这将返回最初发生 Eventobject,因此您应该实际进行强制转换e.getSourcejcombobox 的对象 例如:

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!");
}
}

关于java - 检查可编辑的 jcombobox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37541189/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com