gpt4 book ai didi

java - 使用 Swing 从监听器添加组合框值

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

我是 Swing 新手。我有一个要求,我需要从数据库获取数据并在组合框中弹出,当组合框监听器执行时,它需要加载值。我不确定我哪里出错了,下面代码中的值没有显示。如果我错了,有人可以纠正我吗?代码:

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;

public class ComboBoxSelectionChange extends JFrame
{
public ComboBoxSelectionChange ()
{
initialize();
}

private void initialize ()
{
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.LEFT));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

final JComboBox comboBox = new JComboBox();
comboBox.setEditable(true);
final JTextArea textArea = new JTextArea(5, 15);
textArea.setBorder(new BevelBorder(BevelBorder.LOWERED));

comboBox.addItemListener(new ItemListener() {

public void itemStateChanged (ItemEvent event)
{
String[] items = { "A", "B", "C", "D", "E", "F" };
final DefaultComboBoxModel model = new DefaultComboBoxModel(
items);

comboBox.setModel(model);

}
});

getContentPane().add(comboBox);
getContentPane().add(textArea);
}

public static void main (String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run ()
{
new ComboBoxSelectionChange().setVisible(true);
}
});
}
}

最佳答案

尝试向 JComboBox 添加弹出菜单监听器,如下所示:

comboBox.addPopupMenuListener( PopupMenuListener listener )
{

protected void popupMenuWillBecomeVisible( PopupMenuEvent event )
{
//update your model
}

}

关于java - 使用 Swing 从监听器添加组合框值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26383012/

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