如果您打算在用户进行选择时更改组合框的值,那么您最好使用ActionListener
.
如果您希望每次用户在下拉列表中选择不同的项目时更新组合框(并且,是的,这是一个不同的事件),那么您应该使用ItemListener
但无论哪种情况,过程都是一样的......
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class ComboBoxUpdates {
public static void main(String[] args) {
new ComboBoxUpdates();
}
public ComboBoxUpdates() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JComboBox<String> cb1, cb2, cb3;
public TestPane() {
cb1 = new JComboBox<>(new String[]{"Click me", "Click me", "Click them"});
cb2 = new JComboBox<>();
cb3 = new JComboBox<>();
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
add(cb1, gbc);
add(cb2, gbc);
add(cb3, gbc);
cb1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
cb2.setModel(new DefaultComboBoxModel<String>(new String[]{"item1", "item2", "item3"}));
cb3.setModel(new DefaultComboBoxModel<String>(new String[]{"item4", "item5", "item6"}));
}
});
}
}
}