我在JComboBox
填充列表值时遇到问题。我通过使用类方法(未订阅ActionEvent
)从文件中读取整数值,并成功修改了组合框列表内容。但是,我无法看到UI的内容得到更新。
为什么会这样?但是,当我在按钮的动作侦听器中使用相同的代码时,我可以看到组合框UI使用修改后的列表值进行更新。
如何使用读取文件并修改组合框列表值的简单方法更新组合框UI。
public class NewJFrame extends javax.swing.JFrame{
public NewJFrame() { //Constructor to initialize the Form
initComponents();
}
private void initComponents() {
ButNext = new javax.swing.JButton();
QuestionList = new javax.swing.JComboBox();
….
…. //lines of code
QuestionList.setMaximumRowCount(10);
org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, QuestionList, org.jdesktop.beansbinding.ELProperty.create("${selectedItem}"), QuestionList, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
bindingGroup.addBinding(binding);
QuestionList.addItemListener(new java.awt.event.ItemListener() {
public void itemStateChanged(java.awt.event.ItemEvent evt) {
QuestionListItemStateChanged(evt);
}
});
QuestionList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
QuestionListActionPerformed(evt);
}
});
…
…
bindingGroup.bind();
pack();
setLocationRelativeTo(null);
} //end of initComponents
private void ButNextActionPerformed(java.awt.event.ActionEvent evt) { // If I I click Next button on the UI then the JComboBox is populated with the vales read from the file
….
…. // lines of code
QuesListContent.add(qnumber);
QuestionList.addItem(qnumber);
…. // lines of code
}
private int defineExamstate() throws FileNotFoundException, IOException{ // If I I call this function, then on the UI the JComboBox is NOT populated with the vales read from the file,
//however the values of the list is printed correctly when checked in submain() function
String answersPath=NewJFrame.SavedanswerPath; //file to be read
Scanner input1 = new Scanner(new File(answersPath));
while(input1.hasNextLine())
{
String message = input1.nextLine(); //User answers
switch (message) {
case "START":
startcounter+=1;
lastquestion=0;
break;
case "END":
QuesListContent.clear();
QuestionList.removeAllItems();
maxquestion=0;
endcounter+=1;
break;
default:
record=message.split("Q");
lastquestion=Integer.parseInt(record[0]);
if(!QuesListContent.contains(lastquestion)){
QuesListContent.add(lastquestion);
QuestionList.addItem(lastquestion);
}
break;
}
}
}
protected void submain() throws FileNotFoundException, IOException, Throwable { //Function
…
…. //lines of code
int size = QuestionList.getItemCount();
for(int i=0;i<size;i++) {
Object element = QuestionList.getItemAt(i);
System.out.println("Element at " + i + " = " + element); // Able to print the content of the combo box
}
}
// Variables declaration - do not modify
private javax.swing.JButton ButNext;
private javax.swing.JComboBox QuestionList;
} // end of class definition