我试图在单击按钮时发生不同的事件,这些事件取决于 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");
}
}
}
无论你选择什么,“问题 - 类”总是会打印出“简单”
最佳答案
这是有道理的。您创建 2 个 GUI 实例。一个在主函数中,一个在问题类中。
对于在主函数中实例化的一个:您使用 setVisible 显示框架,并让用户在组合框中进行选择。
对于问题类中实例化的另一个问题,您永远不会在屏幕上显示它,用户永远无法在该实例中选择某些内容。
但是您在该实例中获得了组合框的索引。肯定为零。
您不应在问题类中实例化新的问题类,而应将显示的问题类作为参数传递给问题类,例如 Problem ProblemObject = new Problem(this);
然后将其作为参数放入问题构造函数中,而不是创建一个新的构造函数。
关于java - 获取另一个类中 JComboBox 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52102342/