【问题标题】:Refresh a JComboBox刷新一个 JComboBox
【发布时间】:2012-03-09 14:00:12
【问题描述】:

我有一个组合框,您可以在从表中获取值的代码中看到。 因此,在我单击确定后,表的值会发生变化。 如何在不关闭和打开 jframe 的情况下查看组合框的这些新值? 我今天对 java.awt.EventQueue.invokeLater 和其他工作人员进行了很多研究,但我无法让它发挥作用,我对 java 和一般编程很陌生。 所以这里是代码:

public class Compo extends JFrame implements ActionListener
{//start of class Compo 
//start of variables
private JComboBox<String> CompoBox;
private String array[];
private JButton okButton;
private JPanel panel;
//end of variables
public Compo ()
{//start of Compo method
  super("Example"); 
    panel=new JPanel(null);

   //table =  new String[3];
   array= new String[3];
   array[0]="alpha";
   array[1]="beta";
   array[2]="charlie";

   CompoBox= new JComboBox<>(array);
   CompoBox.setBounds(50, 70, 100, 20);
   panel.add(CompoBox);
   okButton=new JButton("ok");
   okButton.setBounds(50, 120, 70, 30);
   okButton.setActionCommand("ok");
   okButton.addActionListener(this);
   panel.add(okButton);
   add(panel);
   setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   setSize(200, 200);
   setVisible(true);


}//end of compo method
@Override
public void actionPerformed(ActionEvent event)
    {//start of actionperformed
    String testString=event.getActionCommand();
    if (testString.equals("ok"))
    {//start of if
        for (int i = 0; i < array.length; i++)
        {
             String sample= array[i];
             array[i]=sample+"aa";

        }
    }//end of if
}//end of aciton performed


}//end of class Compo 

【问题讨论】:

  • 我在这里订阅的 3 天内如何改进它?
  • 请学习java命名约定并遵守它们
  • 现在的问题是按钮只在第一次点击时才起作用!

标签: java swing jcombobox


【解决方案1】:

这应该是你要找的答案,希望你能接受:

    if (testString.equals("ok")) {
        CompoBox.removeAllItems();
        for (int i = 0; i < array.length; i++) {
            String sample = array[i];
            CompoBox.addItem(sample + "aa");
        }
    }

顺便说一句。通用的 comqo-pox 是这样完成的:

CompoBox = new JComboBox<String>(array);

【讨论】:

  • 我现在就试试吧!谢谢!
【解决方案2】:

您可以直接使用组合框上的addItem(...)removeItem(...) 方法,也可以提供自己的ComboBoxModel 并更改该模型中的数据。

虽然我通常喜欢使用后一个选项(即我自己的模型),但对于您的技能水平,我建议先从添加/删除方法开始。

稍后您可能想要使用默认模型(属于 DefaultComboBoxModel 类并实现 MutableComboBoxModel)。但请记住,在这种情况下,您需要一个演员表并确保您获得了正确类型的模型。

【讨论】:

  • 感谢您的回答。最后,它适用于已启动的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多