【问题标题】:Get Index of JComboBox in another class在另一个类中获取 JComboBox 的索引
【发布时间】:2018-08-30 17:14:31
【问题描述】:

我试图在单击按钮时产生不同的事件,这些事件取决于 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");
        }    

    }

}  

而且无论你选择什么“问题-类”总是会打印出“简单”

【问题讨论】:

  • 是否为程序的下一个“屏幕”转入一个类中的方法?如果是这样,我建议在下一个屏幕的构造函数中发送难度。
  • 呃,我不得不说,我不是很明白……我应该在类的Constructor中使用getDifficulty方法和turn方法吗?然后什么?对不起...
  • 抱歉,我无法理解您的问题。请创建一个minimal reproducible example,以便我们更好地理解它并提供解决方案。
  • 是的,抱歉忘记了。但我现在实现了!

标签: java swing jcombobox


【解决方案1】:

这是有道理的。您创建 2 个 GUI 实例。一个在你的 main 函数中,一个在问题类中。

对于在主函数中实例化的那个:您使用 setVisible 显示框架并让用户在组合框中进行选择。

对于在问题类中实例化的另一个,您永远不会在屏幕上显示它,用户永远无法在该实例中选择某些内容。

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-24
    • 2018-03-28
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多