在另一个 class 中获取 JComboBox 的索引

Get Index of JComboBox in another class

我试图在单击按钮时产生不同的事件,这取决于 JComboBox 的索引。由于实际工程比例子大两段代码不一样 类:

public class GUI {

    private String[] difficultyStrings = {"Easy", "Middle", "Hard"};

    private JFrame frame = new JFrame();

    private JPanel panel = new JPanel();

    private JButton button = new JButton();

    private JComboBox<String> diffucltyBox = new JComboBox(difficultyStrings);

   public static void main(String[] args) {

        GUI guiObject = new GUI();
        guiObject.setGUI();
    }

    private void setGUI() {

        Problem problemObject = new Problem();

        button.setText("What index is selected?");
        button.addActionListener(e -> {

            problemObject.actions();
        });

        panel.add(button);
        panel.add(diffucltyBox);

        frame.add(panel);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setMinimumSize(new Dimension(700, 700));
        frame.setSize(800, 800);
        frame.setTitle("SuperTicTacToe");
        frame.setVisible(true);
    }

    protected int getDifficulty() {

        int difficulty;
        difficulty = diffucltyBox.getSelectedIndex();

        return difficulty;
    }

}

并且:

public class Problem {

    public void actions() {

        GUI guiObject = new GUI();

        if(guiObject.getDifficulty() == 0) {

            System.out.println("Easy");
        }   

        else if(guiObject.getDifficulty() == 1) {

            System.out.println("Middle");
        }    

        else if(guiObject.getDifficulty() == 2) {

            System.out.println("Hard");
        }    

    }

}  

而且无论您 select 做什么,"Problem - class" 都会打印出 "Easy"

有道理。您创建了 2 个 GUI 实例。一个在你的主要功能中,一个在问题中 class.

对于在 main 函数中实例化的那个:使用 setVisible 显示框架并让用户在组合框中创建一个 selection。

对于问题中实例化的另一个 class 你永远不会在屏幕上显示它,用户永远无法 select 在那个实例中的东西。

但是您在该实例中获得了组合框的索引。肯定是零。

你不应该在问题中实例化一个新的 class 而是将显示的作为参数传递给问题 class 例如 Problem problemObject = new Problem(this);

然后在问题构造函数中将其作为参数而不是创建一个新参数。