两个组合框,改变其中一个组合框的值,另一个组合框的值也会相应改变。请问各位,在Swing中如何实现?

解决方案 »

  1.   

    public class Demo extends JFrame implements ActionListener{

    private static final long serialVersionUID = -6336187772824409988L;
    private JPanel rootPanel = new JPanel();
    private JComboBox box1 = new JComboBox(new String[]{"1","2","3","4"});
    private JComboBox box2 = new JComboBox(new String[]{"one","two","three","four"});
    public Demo(){
    init();
    }

    public void init(){
    this.setSize(300,300);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setContentPane(rootPanel);

    rootPanel.add(box1);
    rootPanel.add(box2);

    box1.addActionListener(this);
    box2.addActionListener(this);
    } public void actionPerformed(ActionEvent e) {
    if(e.getSource() == box1){
    int selectedIndex = box1.getSelectedIndex();
    if(selectedIndex > -1 && selectedIndex < box1.getItemCount()){
    box2.setSelectedIndex(selectedIndex);
    }
    }else if(e.getSource() == box2){
    int selectedIndex = box2.getSelectedIndex();
    if(selectedIndex > -1 && selectedIndex < box2.getItemCount()){
    box1.setSelectedIndex(selectedIndex);
    }
    }

    }

    public static void main(String[] args){
    Demo d = new Demo();
    d.setVisible(true);
    }
    }
      

  2.   

    这里只是简单的写死的item Object,实际的数据加载同样