我有3个JCombobox IN MY Converter程序一个用于类别,两个用于选择要执行的功能;我希望程序做的是当用户在一个JCombobox中选择一个类别时,两个JCombobox将自动更改与所选类别相关的内容(当选择一个其他的chage值时,请帮助我使用JCombobox更改项目的功能);
答案 0 :(得分:5)
正如JB Nizet所说,这是一个简短的例子:
import java.awt.BorderLayout;
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.SwingUtilities;
public class ConnectedComboBoxDemo extends JFrame implements ActionListener {
private static final long serialVersionUID = 6108579736224814080L;
private JPanel panel;
private JComboBox combo1;
private JComboBox combo2;
public ConnectedComboBoxDemo() {
panel = new JPanel();
String[] combo1Item = new String[]{"val1", "val2", "val3"};
combo1 = new JComboBox(combo1Item);
combo1.addActionListener(this);
String[] combo2Item = new String[]{"val11", "val12", "val13"};
combo2 = new JComboBox(combo2Item);
panel.setLayout(new BorderLayout());
panel.add(combo1, BorderLayout.WEST);
panel.add(combo2, BorderLayout.EAST);
setContentPane(panel);
pack();
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
String selectedValue = combo1.getSelectedItem().toString();
String[] combo2Item = null;
DefaultComboBoxModel model = (DefaultComboBoxModel) combo2.getModel();
model.removeAllElements();
if(selectedValue.equals("val1")){
combo2Item = new String[]{"val11", "val12", "val13"};
} else if(selectedValue.equals("val2")){
combo2Item = new String[]{"val21", "val22", "val23"};
} else if(selectedValue.equals("val3")){
combo2Item = new String[]{"val31", "val32", "val33"};
}
for(String val : combo2Item){
model.addElement(val);
}
}
public static void main(String... args){
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new ConnectedComboBoxDemo();
}
});
}
}
希望这会对你有所帮助。
答案 1 :(得分:3)
只需将ActionListener添加到第一个组合框,并在动作侦听器的actionPerformed
方法中,在第一个组合中获取所选值,并更改第二个组合显示的值。
答案 2 :(得分:3)
ItemListener使用ActionListener而不是JComboBox,将Listener放在一起example about ActionListener with ItemListener for two JComboBoxes
答案 3 :(得分:-1)
尝试使用 itemStateChanged (java.awt.event.ItemEvent evt)