简体   繁体   English

检查可编辑的jcombobox

[英]check for editable jcombobox

I cant lend inside the if check of keyTyped method. 我无法借用keyTyped方法的if检查。 There is followiing part of code: 代码的后续部分:

here I initialise the Combobox: 在这里我初始化了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 );
}

at this point i check what was typed in: 在这一点上,我检查输入的内容:

@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;
        }
      }
  }
}

In the keyTyped method I do check 在keyTyped方法中我做检查

if ( e.getSource() instanceof JComboBox )

why it doesnt go inside of this if Statement? 为什么它不会进入这个if语句?

e.getSource() doesn't return an object of JComboBox according to https://docs.oracle.com/javase/7/docs/api/java/util/EventObject.html this is the method declaration of getSource(); e.getSource()根据https://docs.oracle.com/javase/7/docs/api/java/util/EventObject.html不返回JComboBoxobject ,这是getSource()的方法声明; public Object getSource() this will return The object on which the Event initially occurred so you should actually cast the e.getSource to an object of jcombobox ex: public Object getSource()这将返回Event最初发生的object ,因此您应该将e.getSource实际转换为jcombobox ex的对象:

if(cboDay == (jcombobox)e.getSource())

you can achieve the same functionality by using actioncommand ex: 您可以使用actioncommand ex实现相同的功能:

 cboDay.setActionCommand("combo"); 

 public void keyTyped( KeyEvent e )
     String action = e.getActionCommand();
      if (action.equals("combo")) {
      System.out.println("done!");
      }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM