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