java - 程序运行时向 JComboBox 添加项目

标签 java user-interface jcombobox

我的程序有一个 GUI,用户首先选择一个按钮来加载 Excel 文件。然后 Excel 文件的内容列在 JTextArea 和 JComboBox 中。如图所示,虽然 JTextArea 包含一些文本,但 JComboBox 是空的。我调试了代码并可以验证 JComboBox 的变量 (TheGene) 添加了该项目。换句话说,str 在每次迭代中都包含 AARS、AARS2...。

enter image description here

描述 JComboBox 在创建 JComboBox 后静态添加项目的示例。我想在运行某些内容后添加项目(当按钮的工作完成时)。

我使用的是Netbeans的框架设计器,它会自动生成以下代码

public class TheFrame extends javax.swing.JFrame 
{
  ...
  private javax.swing.JComboBox<String> TheGene;
  private void initComponents() {
    ...
    TheGene = new javax.swing.JComboBox<>();
    TheGene.setMaximumRowCount(20);
    TheGene.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        TheGeneActionPerformed(evt);
      }
    });
    ...
  }
  private void TheGeneActionPerformed(java.awt.event.ActionEvent evt)
  {                                        
    // TODO add your handling code here:
    int n = theFile.getGeneNumberFromFile();
    for (int i = 0; i < n; i++){
      String str = theFile.getGeneNameFromFile( i );
      TheGene.addItem(str);
  }
}

最佳答案

您可以为您的 JComboBox 使用模型,例如:

DefaultComboBoxModel<String> model = new DefaultComboBoxModel<String>();
JComboBox TheGene = new JComboBox( model );

然后单击加载基因列表按钮:

private void TheGeneActionPerformed(java.awt.event.ActionEvent evt)
{                       
    model.removeAllElements();               
    // TODO add your handling code here:
    int n = theFile.getGeneNumberFromFile();
    for (int i = 0; i < n; i++) {
      String str = theFile.getGeneNameFromFile( i );
      model.addElement(str);
   }
}

这应该填充组合的项目。

关于java - 程序运行时向 JComboBox 添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43686453/

相关文章:

Java:在定时间隔后运行脚本

python - PyQt:获取当前标签号

java - JTable JComboBox 默认在列表展开时显示第一项

java - 如何对选定的数据进行分组?

java - A<T extends B> 和 A< 有什么区别?延伸 B>?

java - 在Java中,如何实现像文件资源管理器这样的东西?

java - 我的 Jcombobox 似乎正在工作,但是当我在其中进行任何选择时,程序似乎没有注册更改

java - 如何将 Unicode 符号添加到组合框

java - 如何去掉输出到txt的程序状态?

python - 关于 Enthought Traits/TraitsUI for Python 桌面开发的看法