【发布时间】: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,以便我们更好地理解它并提供解决方案。
-
是的,抱歉忘记了。但我现在实现了!