我有3个JCombobox IN MY Converter程序,一个用于类别,另外两个用于选择要执行的功能;我要程序执行的操作是,当用户在一个JCombobox中选择一个类别时,两个JCombobox会自动更改与所选类别相关的内容(请在选择一个其他Cage值时帮助我使用JCombobox Change Items的功能);
最佳答案
正如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();
}
});
}
}
希望这会帮助你。