使用SwingX AutoCompleteDecorator刷新JComboBox

时间:2014-10-17 13:22:11

标签: java swing jcombobox swingx

我在JComboBox上使用SwingX AutoCompleteDecorator。一切正常,除了我希望我的用户可以更改我的对象的名称,名称也显示在组合框中。问题是我可以刷新我的组合框,但自动完成装饰器中显示的字符串保持不变,如图所示: Problem

刷新组合框的代码如下所示:

try {
   Aannemer a = getNewAannemer();
   MainController.getInstance().updateAannemer(a);
   aannemerBox.revalidate();
   aannemerBox.repaint();
} catch (Exception ex) {
   //...
}

当我从组合框中重新选择对象时,字符串会更新。 我还尝试使用组合框的个性化渲染器和编辑器。

我还能如何刷新组合框中显示的字符串?

1 个答案:

答案 0 :(得分:0)

使用当前代码,很难说出现了什么问题。以下代码对我来说很好用

import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.WindowConstants;
import java.awt.BorderLayout;
import java.awt.EventQueue;

public class AutoCompleteCombobox {

  public static void main( String[] args ) {
    EventQueue.invokeLater( () -> {
      JFrame frame = new JFrame( "TestFrame" );

      JComboBox<String> comboBox = new JComboBox<>(  );
      DefaultComboBoxModel<String> model = new DefaultComboBoxModel<>(  );
      model.addElement( "First" );
      model.addElement( "Second" );
      comboBox.setModel( model );
      comboBox.setEditable( true );

      AutoCompleteDecorator.decorate( comboBox );

      frame.getContentPane().add( comboBox );

      JButton button = new JButton( "Add item" );
      button.addActionListener( e -> {
        String selectedItem = ( String ) comboBox.getSelectedItem();
        if ( comboBox.getSelectedIndex() == -1 ){
          model.addElement( selectedItem );
        }
      } );
      frame.getContentPane().add( button, BorderLayout.SOUTH );

      frame.pack();
      frame.setVisible( true );
      frame.setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );
    } );
  }
}
  • 自动完成按预期工作
  • 我可以输入新项目
  • 使用添加按钮时,我可以添加新项目,自动完成功能很好

简而言之,我无法重现您的问题。请在您的问题中发布一段代码,以便我们重现问题。