我的Java(Eclipse)中的ActionListener存在问题。 该程序应该问你关于数学中不同主题的问题。以下是代码的一部分,其中包括问题:
public Frame () {
c = getContentPane();
c.setLayout(new BorderLayout());
menuBar = new JMenuBar();
menu = new JMenu("Test");
menu.setMnemonic(KeyEvent.VK_A);
addition = new JMenuItem("Addition");
addition.setMnemonic(KeyEvent.VK_B);
menu.add(addition);
minus = new JMenuItem("Subtraction");
minus.setMnemonic(KeyEvent.VK_C);
menu.add(minus);
setJMenuBar(menuBar);
menuBar.add(menu);
answer = new JButton("Answer");
c.add(answer, BorderLayout.SOUTH);
next = new JButton("Next");
c.add(next, BorderLayout.EAST);
back = new JButton("Back");
c.add(back, BorderLayout.WEST);
beschriftung = new JLabel();
beschriftung.setText("Welcome! Please choose your desired operation at the top.");
beschriftung.setVerticalTextPosition(JLabel.CENTER);
beschriftung.setHorizontalAlignment(JLabel.CENTER);
c.add(beschriftung,BorderLayout.CENTER);
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
i = 1+dice.nextInt(99);
j = 1+dice.nextInt(99);
k = i + j;
beschriftung.setText("Next Question: " + i + "+" + j);
}
});
addition.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent a) {
beschriftung.setText("Addition Questions!");
c.remove(nextminus);
next = new JButton("Next");
c.add(next, BorderLayout.EAST);
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent b) {
i = 1+dice.nextInt(99);
j = 1+dice.nextInt(99);
k = i + j;
beschriftung.setText("Next Question: " + i + "+" + j);
}
});
answer2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent d) {
beschriftung.setText(i + "+" + j + "= " + k);
}
});
}
});
minus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
beschriftung.setText("Subtraction Questions!");
c.remove(next);
nextminus = new JButton("Next!");
c.add(nextminus, BorderLayout.EAST);
nextminus.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent f) {
i = 1+dice.nextInt(99);
j = 1+dice.nextInt(99);
k = i - j;
beschriftung.setText("Next Question: " + i + "-" + j);
}
});
answer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent g) {
beschriftung.setText(i + "-" + j + "= " + k);
}
});
}
});
}
当我在添加标签中点击JButton“answer”时,它不会输出任何内容。
任何人都知道解决方案吗?
答案 0 :(得分:0)
看起来您正在将动作侦听器设置为错误的按钮。尝试在添加菜单栏项的动作侦听器中使用answer.addActionListener()
代替answer2.addActionListener()
。