JCombo +覆盖toString

时间:2014-10-06 18:17:44

标签: java jcombobox tostring

好吧,我正在开展一个相当大的计划。

我会尝试只投入你需要的东西。

现在, comboBox 正在填充(使用覆盖toString),并且第一项已被选中。

当我选择不同的参数并强制更改comboBox的内容时,新列表会被放入comboBox并再次选择第一个项目。

我可以看到更新,所以我知道它正在填写。

问题,当我在comboBox中选择任何内容时,没有任何反应。

第一项保持选中状态,我的System.out.println行都没有打印,因此没有执行任何操作。

当我删除我的覆盖toString时,一切都按预期工作。

过去的奇怪部分是删除了此覆盖toString后,它会回到 覆盖toString的父类。

发生了什么事?

根据我的理解,toString字面上会更改显示的内容,但不会更改数据。

我将对象添加到comboBox,但显示了一些信息。

public class Belt extends Part{
    //variable initialization and methods
    @override
    public String toString(){
    String display = this.getCode() + " - " + this.color;
    return display;
}

public final class Something implements ActionListener{
    //variable initialization and methods
    //there are several methods that call the fillBeltCombo()

    GridBagConstraints c = new GridBagConstraints();
    private void pad(GridBagConstraints c){
        c.anchor = GridBagConstraints.NORTHWEST;
        c.weightx = 1;
        c.insets.left = 10;
        c.insets.right = 10;
        c.insets.top = 5;
        c.insets.bottom = 5;
    }

    beltCombo = new JComboBox();
    beltCombo.setVisible(true);
    c.gridwidth = 2;
    c.gridx = 4;
    c.gridy = 9;
    beltCombo.addActionListener((ActionEvent eventBelt) -> {
        JComboBox beltCodeCombo1 = (JComboBox) eventBelt.getSource();
        if(beltCombo.getItemCount()>0){
            currentProduct.setBelt((Belt)beltCodeCombo1.getSelectedItem());
        }else{/*do nothing*/}
    });
    pane.add(beltCombo, c);

    public static void fillBeltCombo(ArrayList<Belt> list){
        beltCombo.removeAllItems();
        int size = list.size();
        for(int x=0; x<size; x++){
            beltCombo.addItem(list.get(x));
        }
    }
}

2 个答案:

答案 0 :(得分:0)

因此,根据markspace的建议,我创建了一个MCVE(尽我所能,同时保持我的程序正在做的事情)。那里的一切都在我真实的程序中完成,虽然更复杂。我不确定我的程序出错了什么,但是我确实发现我想要做的事情是可能的,我可以在使用Override toString时从第二个comboBox中选择一个项目在子类中。现在我只需要在实际代码中跟踪问题......

package minitest;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MainClass {
    JFrame frame;
    JPanel pane;
    JLabel label1, label2;
    JComboBox comboA, comboB;
    ArrayList<Parent> parents = new ArrayList<>();
    ArrayList<Grandchild> grandkids = new ArrayList<>();
    Parent parent1 = new Parent(1);
    Parent parent2 = new Parent(2);
    Grandchild grandkid1 = new Grandchild(1,1,"oneone");
    Grandchild grandkid2 = new Grandchild(1,2,"onetwo");
    Grandchild grandkid3 = new Grandchild(2,1,"twoone");
    Grandchild grandkid4 = new Grandchild(2,2,"twotwo");
    public class Parent{
        protected int num;
        public Parent(int num){
            this.num = num;
        }
        @Override public String toString(){
            return String.valueOf(num);
        }
    }
    public class Child extends Parent{
        private double dbl;
        public Child(int num, double dbl){
            super(num);
            this.dbl = dbl;
        }
    }
    public class Grandchild extends Child{
        private String str;
        public Grandchild(int num, double dbl, String str){
            super(num, dbl);
            this.str = str;
        }
        @Override public String toString(){
            return this.num + " - " + this.str;
        }
    }
    //Fill passed combo with each item from passed ArrayList
    public void fillCombo(ArrayList list, JComboBox target){
        target.removeAllItems();
        int size = list.size();
        for(int x = 0; x < size; x++){
            target.addItem(list.get(x));
        }
    }
    //remove all items from combobox except selected item
    public void comboUpdate(JComboBox combo){
        if(combo.getSelectedItem()==null){
            /*donothing*/
        }else{
            int size = (combo.getItemCount()-1);
            System.out.println("size: "+size);
            for (int x=size; x>=0; x--) {
                if(combo.getSelectedItem().equals(combo.getItemAt(x))){
                    /*donothing*/
                    System.out.println(combo.getSelectedItem()+" is selected");
               }else{
                    System.out.println(combo.getItemAt(x)+" is now removed");
                    combo.removeItemAt(x);
                }
            }
        }
    }
    //Add each item from passed ArrayList if not equal to the selected item
    public void removeDuplicate(JComboBox combo, ArrayList array){
        System.out.println("removeDuplicate: "+array);
        if(combo.getSelectedItem()==null){
            System.out.println("combo.getSelectedItem==null");
            fillCombo(array, combo);
        }else{
            boolean validChoice = false;
            int arraySize = array.size();
                for(int x = 0; x < arraySize; x++){
                    if(combo.getSelectedItem().equals(array.get(x))){
                        System.out.println(combo.getSelectedItem()+" == "+array.get(x));
                        validChoice = true;
                    }else{
                        System.out.println(combo.getSelectedItem()+" != "+array.get(x));
                        combo.addItem(array.get(x));
                    }
                }
            if(validChoice == false){
                System.out.println("removeItemAt(0)");
                combo.removeItemAt(0);
            }
        }
    }
//fill comboB with grandchild objects whos int match the selected partent objects int
    public void fillComboB(){
        System.out.println("grandkids: "+grandkids);
        ArrayList<Grandchild> temp = copyArrayList(grandkids);
        System.out.println("temp: "+temp);
        comboUpdate(comboB);
        int size = (temp.size()-1);
        for(int x=size; x>=0; x--){
            if(temp.get(x).num==((Parent)comboA.getSelectedItem()).num){
                /*donothing*/
                System.out.println("donothing: temp.get("+x+")="+temp.get(x));
            }else{
                System.out.println("temp.remove("+x+")="+temp.get(x));
                temp.remove(x);
            }
        }
        removeDuplicate(comboB, temp);
    }
    public ArrayList copyArrayList(ArrayList list){
        ArrayList<Object> temp = new ArrayList<>();
        int size = list.size();
        for(int x=0; x<size; x++){
            temp.add(list.get(x));
        }
        return temp;
    }
    public MainClass(){
        parents.add(parent1);
        parents.add(parent2);
        grandkids.add(grandkid1);
        grandkids.add(grandkid2);
        grandkids.add(grandkid3);
        grandkids.add(grandkid4);
        frame = new JFrame("frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        pane = new JPanel();
        pane.setLayout(new GridBagLayout());
        GridBagConstraints c = new GridBagConstraints();
        comboA = new JComboBox();
        fillCombo(parents, comboA);
        c.gridx = 0;
        c.gridy = 0;
        comboA.addActionListener((ActionEvent eventComboA) -> {
            System.out.println("eventComboA");
            JComboBox comboA1 = (JComboBox) eventComboA.getSource();
            if(comboA.getItemCount()>0){
                System.out.println("comboA.getItemCount>0: "+(Parent)comboA1.getSelectedItem());
                fillComboB();
            }
        });
        pane.add(comboA, c);

        comboB = new JComboBox();
        c.gridx = 0;
        c.gridy = 1;
        comboB.addActionListener((ActionEvent eventComboB) -> {
            System.out.println("eventComboB");
            JComboBox comboB1 = (JComboBox) eventComboB.getSource();
            if(comboB.getItemCount()>0){
                System.out.println("comboB.getItemCount>0: "+(Grandchild)comboB1.getSelectedItem());
            }
        });
        pane.add(comboB, c);

        frame.setContentPane(pane);
        frame.setSize(150,150);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
    private static void runGUI(){
        JFrame.setDefaultLookAndFeelDecorated(false);
        MainClass create = new MainClass();
    }
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(() -> {
            runGUI();
        });
    }
}

答案 1 :(得分:0)

Aright,所以基于昨天的成功创作(我感到沮丧),我继续填补骨架,直到它再次破裂。   - 调整后的类,以反映我正在处理的实际数据类型。   - 添加了我的覆盖等于方法&lt; ------- problem

当我最初创建equals覆盖时,所有的toStrings都是相同的,并且显示在comboBox中。 所以等于覆盖看起来像

@Override public boolean equals(Object other){
    if (other == null) return false;
    return (String.valueOf(other)).equals(this.description);
}

问题在于,当我被要求更改comboBox中显示的内容时,我没有意识到comboBox似乎使用了等于check。新的其他对象是

this.getCode() + " - " + this.color;

并将其与num进行比较,后者返回false。

现在纠正我,如果我错了,但故事的道德似乎是: JComboBox不会让你从列表中选择一些不等于列表中的东西。所以因为我的equals override改变了对象的比较方式:  对象的字符串值,与对象的字符串变量进行比较 - 同一个对象并不等于自己。 调整后的代码:

@Override public boolean equals(Object other){
    if (other == null) return false;
    return ((Parent)other).description.equals(this.description);
}