根据Java中的控件值选择List中的特定值

时间:2016-01-28 03:14:59

标签: java eclipse swing

我有一个String列表,它的值类似于{“val1”,“val2”,“val3”,“val4”} 我有三个不同的组合框。每个组合框都有超过5个项目。

现在我想从列表中只选择一个具有组合框项目组合的值。我已经尝试使用if-else和switch语句,但它真的很乏味。那么解决这类问题的最佳方法是什么? GUI部分的屏幕截图。

GUI

提前致谢。

我有一个像这样的长嵌套开关案例

 switch(comboBox1_value)
   {
            case "X1" :
                switch(comboBox2_value)
                {
                case "X1":
                    // select val1 from list
                    break;
                case "X2":
                    // select val2 from list
                    break;

                case "K1":
                    // select val3 from list
                    break;
                case "K2":
                    // select val1 from list
                    break;
                }
           .
           .
           .
    }

1 个答案:

答案 0 :(得分:0)

public class Main {

    private static String[] X_VALUES = {"x1","x2","x3","x3",};
    private static String[] Y_VALUES = {"y1","y2","y3","y3",};
    private static String[] Z_VALUES = {"z1","z2","z3","z3",};

    public static void main(String[] args) {

        JComboBox<String> x_c = new JComboBox<>(X_VALUES);
        JComboBox<String> y_c = new JComboBox<>(Y_VALUES);
        JComboBox<String> z_c = new JComboBox<>(Z_VALUES);

        java.util.List<String> l = new ArrayList<>();

        Stream.of(X_VALUES)
                .forEach(x -> {
                    Stream.of(Y_VALUES)
                    .forEach(y -> {
                        Stream.of(Z_VALUES)
                        .forEach(z -> {
                            l.add("X:" + x + ", Y: " + y + ", Z: " + z);
                        });
                    });
                });

        JList<String> list = new JList<>(l.toArray(new String[l.size()]));

        ActionListener al = e -> { list.setSelectedValue("X:" + x_c.getSelectedItem() + ", Y: " + y_c.getSelectedItem() + ", Z: " + z_c.getSelectedItem(), true); };

        x_c.addActionListener(al);
        y_c.addActionListener(al);
        z_c.addActionListener(al);

        JFrame f = new JFrame();
        JPanel p = new JPanel();
        p.add(x_c);
        p.add(y_c);
        p.add(z_c);
        p.add(new JScrollPane(list));

        f.setContentPane(p);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.pack();
        f.setVisible(true);

    }

}