如何更改具有相同索引-java的两个组合框的项目?

时间:2021-12-11 12:43:14

I have two comboboxes, one for choosing 'number' and another one for choosing 'name'. When I select an item from number ,the name must be changed according to the index of number and vice versa`

我有两个组合框,一个用于选择“数字”,另一个用于选择“名称”。当我从数字中选择一个项目时,必须根据数字索引更改名称,反之亦然

Click here to see image

点击这里查看图片

 private void nameItemStateChanged(java.awt.event.ItemEvent evt) 
    {                                                
         int i = name.getSelectedIndex();
         number.setSelectedIndex(i);
        //It will changes number according to name  
        //Used ItemEvent        
    }  



private void numberItemStateChanged(java.awt.event.ItemEvent evt) 
   {                                                
         int i = number.getSelectedIndex();
         name.setSelectedIndex(i);
         //It will change name according to number
         //used ItemEvent
    }  

These codes are making exceptions because both are using ItemStateChanged event..So suggest another method..

这些代码正在异常,因为两者都在使用ItemStateChanged事件。所以建议另一种方法..

1 个解决方案

#1


1  

You appear to be giving your class two methods with the same signature, and the compile won't allow you to do this. If so, then the solution is not to do this. If you absolutely need two JComboBoxes tightly tied together in a one-to-one relationship, something that I don't recommend that you do, then either give each combo box its own ChangeListener, or better yet, have them share the same model but use a different renderer for each.

您似乎为您的类提供了两个具有相同签名的方法,并且编译将不允许您执行此操作。如果是这样,那么解决方案就是不这样做。如果你绝对需要两个JComboBox紧密地绑在一起的一对一关系,我不建议你做的事情,那么要么给每个组合框自己的ChangeListener,或者更好,让它们共享相同的模型,但为每个渲染器使用不同的渲染器。

For a more specific answer, please update your question, including posting a valid minimal example program or SSCCE (please check out the links).

如需更具体的答案,请更新您的问题,包括发布有效的最小示例程序或SSCCE(请查看链接)。

For example, here are two JComboBoxes that share the same model, a model that holds "Customer" objects. The Customer class has only two private instance fields, an int "id" field and a String "name" field. So again both combo boxes are holding the same data.

例如,这里有两个共享相同模型的JComboBox,一个包含“Customer”对象的模型。 Customer类只有两个私有实例字段,一个int“id”字段和一个String“name”字段。因此,两个组合框都保持相同的数据。

But they display the data differently by using different cell renderers, one that shows only the id, and the other that shows just the name. You only need to add a ChangeListener to one, and it will be activated if either combobox's selection is changed, since changing one changes the other (again they share the same model).

但是它们通过使用不同的单元格渲染器来显示数据,一个只显示id,另一个只显示名称。您只需要将ChangeListener添加到一个,如果更改了组合框的选择,它将被激活,因为更改组合框会改变另一个(同样它们共享相同的模型)。

import java.awt.Component;
import java.awt.event.ItemEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class LinkedComboEg extends JPanel {
    private DefaultComboBoxModel<Customer> comboModel = new DefaultComboBoxModel<>();
    private JComboBox<Customer> idCombo = new JComboBox<>(comboModel);
    private JComboBox<Customer> nameCombo = new JComboBox<>(comboModel);

    public LinkedComboEg() {
        comboModel.addElement(new Customer(1001, "Doc"));
        comboModel.addElement(new Customer(1002, "Donald Trump"));
        comboModel.addElement(new Customer(1003, "Bashful"));
        comboModel.addElement(new Customer(1004, "Grumpy"));
        comboModel.addElement(new Customer(1005, "Sneezy"));
        comboModel.addElement(new Customer(1006, "Happy"));
        comboModel.addElement(new Customer(1007, "Sleepy"));

        idCombo.setRenderer(new IdRenderer());
        nameCombo.setRenderer(new NameRenderer());
        nameCombo.setSelectedIndex(-1); // none selected to start

        // add an item listener to just one combo box. Either will do
        idCombo.addItemListener(ie -> {
            Customer selection = (Customer) ie.getItem();
            if (ie.getStateChange() == ItemEvent.SELECTED && selection != null) {
                System.out.printf("Selected id: %s;   Selected name: %s%n", 
                        selection.getId(),
                        selection.getName());
            }
        });

        add(new JLabel("ID Number:"));
        add(idCombo);
        add(Box.createHorizontalStrut(20));
        add(new JLabel("Name:"));
        add(nameCombo);
    }

    // renderer to add to the idCombo so that it displays the Customer's ID
    private class IdRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            if (value == null) {
                value = "";
            } else {
                value = ((Customer) value).getId();
            }
            return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        }
    }

    // renderer to add to the nameCombo so that it displays the Customer's Name
    private class NameRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            if (value == null) {
                value = "";
            } else {
                value = ((Customer) value).getName();
            }
            return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        }
    }

    private static void createAndShowGui() {
        LinkedComboEg mainPanel = new LinkedComboEg();

        JFrame frame = new JFrame("Linked Combo Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

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

public class Customer {
    private int id;
    private String name;

    public Customer(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Customer other = (Customer) obj;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

}

#1


1  

You appear to be giving your class two methods with the same signature, and the compile won't allow you to do this. If so, then the solution is not to do this. If you absolutely need two JComboBoxes tightly tied together in a one-to-one relationship, something that I don't recommend that you do, then either give each combo box its own ChangeListener, or better yet, have them share the same model but use a different renderer for each.

您似乎为您的类提供了两个具有相同签名的方法,并且编译将不允许您执行此操作。如果是这样,那么解决方案就是不这样做。如果你绝对需要两个JComboBox紧密地绑在一起的一对一关系,我不建议你做的事情,那么要么给每个组合框自己的ChangeListener,或者更好,让它们共享相同的模型,但为每个渲染器使用不同的渲染器。

For a more specific answer, please update your question, including posting a valid minimal example program or SSCCE (please check out the links).

如需更具体的答案,请更新您的问题,包括发布有效的最小示例程序或SSCCE(请查看链接)。

For example, here are two JComboBoxes that share the same model, a model that holds "Customer" objects. The Customer class has only two private instance fields, an int "id" field and a String "name" field. So again both combo boxes are holding the same data.

例如,这里有两个共享相同模型的JComboBox,一个包含“Customer”对象的模型。 Customer类只有两个私有实例字段,一个int“id”字段和一个String“name”字段。因此,两个组合框都保持相同的数据。

But they display the data differently by using different cell renderers, one that shows only the id, and the other that shows just the name. You only need to add a ChangeListener to one, and it will be activated if either combobox's selection is changed, since changing one changes the other (again they share the same model).

但是它们通过使用不同的单元格渲染器来显示数据,一个只显示id,另一个只显示名称。您只需要将ChangeListener添加到一个,如果更改了组合框的选择,它将被激活,因为更改组合框会改变另一个(同样它们共享相同的模型)。

import java.awt.Component;
import java.awt.event.ItemEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class LinkedComboEg extends JPanel {
    private DefaultComboBoxModel<Customer> comboModel = new DefaultComboBoxModel<>();
    private JComboBox<Customer> idCombo = new JComboBox<>(comboModel);
    private JComboBox<Customer> nameCombo = new JComboBox<>(comboModel);

    public LinkedComboEg() {
        comboModel.addElement(new Customer(1001, "Doc"));
        comboModel.addElement(new Customer(1002, "Donald Trump"));
        comboModel.addElement(new Customer(1003, "Bashful"));
        comboModel.addElement(new Customer(1004, "Grumpy"));
        comboModel.addElement(new Customer(1005, "Sneezy"));
        comboModel.addElement(new Customer(1006, "Happy"));
        comboModel.addElement(new Customer(1007, "Sleepy"));

        idCombo.setRenderer(new IdRenderer());
        nameCombo.setRenderer(new NameRenderer());
        nameCombo.setSelectedIndex(-1); // none selected to start

        // add an item listener to just one combo box. Either will do
        idCombo.addItemListener(ie -> {
            Customer selection = (Customer) ie.getItem();
            if (ie.getStateChange() == ItemEvent.SELECTED && selection != null) {
                System.out.printf("Selected id: %s;   Selected name: %s%n", 
                        selection.getId(),
                        selection.getName());
            }
        });

        add(new JLabel("ID Number:"));
        add(idCombo);
        add(Box.createHorizontalStrut(20));
        add(new JLabel("Name:"));
        add(nameCombo);
    }

    // renderer to add to the idCombo so that it displays the Customer's ID
    private class IdRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            if (value == null) {
                value = "";
            } else {
                value = ((Customer) value).getId();
            }
            return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        }
    }

    // renderer to add to the nameCombo so that it displays the Customer's Name
    private class NameRenderer extends DefaultListCellRenderer {
        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index,
                boolean isSelected, boolean cellHasFocus) {
            if (value == null) {
                value = "";
            } else {
                value = ((Customer) value).getName();
            }
            return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
        }
    }

    private static void createAndShowGui() {
        LinkedComboEg mainPanel = new LinkedComboEg();

        JFrame frame = new JFrame("Linked Combo Example");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

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

public class Customer {
    private int id;
    private String name;

    public Customer(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Customer other = (Customer) obj;
        if (id != other.id)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }

}