gpt4 book ai didi

java - ItemListener 不改变值 Java

转载 作者:行者123 更新时间:2023-12-01 22:45:44 25 4
gpt4 key购买 nike

我编写了这段代码,它应该在从组合框中选择一个项目后更改 JLabel 中的值。当我运行应用程序时,JLabel 中会显示该值,但是当我在组合框中选择其他值时,JLabel 中的值不会更改。有谁知道问题出在哪里吗?

comboBox = new JComboBox<String>();
comboBox.setBounds(172, 50, 106, 22);
frmAccountPayable.getContentPane().add(comboBox);

comboBox.addItemListener(new ItemListener(){

public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
String expenseCode = item.toString();

try {
String sql2 = "SELECT `Account No`, `Expense Code` FROM `database`.`expense_code_master` " +
"WHERE `Expense Code` = '" + expenseCode + "'";
PreparedStatement pst2 = conn.prepareStatement(sql2);
ResultSet rs = pst2.executeQuery();
String accNo1 = null;
while (rs.next()){
accNo1 = rs.getString("Account No");
}

lblTesting = new JLabel(accNo1);
lblTesting.setBounds(496, 49, 106, 22);
frmAccountPayable.getContentPane().add(lblTesting);

}catch (Exception ex) {
System.out.println("Error: "+ex);

}
}
}
});

最佳答案

如果您的组件中已有 JLabel,则无需为每次状态更改重新创建一个。

将该部分移动到您还添加 comboBox 的位置:

lblTesting = new JLabel(accNo1);
lblTesting.setBounds(496, 49, 106, 22);
frmAccountPayable.getContentPane().add(lblTesting);

但使用默认构造函数。

并且不必每次添加新标签,只需调用:

lblTesting.setText(accNo1);

话虽如此,我想在您的示例中您添加了新标签,但仅显示第一个标签 - 取决于您的布局。

关于java - ItemListener 不改变值 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25405440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com