问题字段应包含36个问题,这些问题的答案在网格中的36个按钮上。
我在问题字段中显示36问题从用户点击正确的按钮时开始显示问题字段然后在字段中显示问题2显示是1 + 1等问题36我遇到了问题
那我如何得到一个问题JLabel并通过JLabel的setText(...)方法交换它所拥有的文本
这是我的代码
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionListener;
import java.util.*;
import javax.swing.*;
class NewClass {
final int ROWS = 6;
final int COLUMNS = 6;
JButton[] buttons = new JButton[ROWS*COLUMNS];
JLabel statusLabel = new JLabel("",JLabel.CENTER);
java.util.List<Integer> buttonNumbers = new ArrayList<Integer>();
int buttonCounter = 1;
public NewClass() {
JPanel buttonPanel = new JPanel(new GridLayout(ROWS,COLUMNS));
ButtonListener listener = new ButtonListener(NewClass.this);
for(int x = 0, y = ROWS*COLUMNS; x < y; x++){
buttons[x] = new JButton();
buttons[x].addActionListener(listener);
buttonPanel.add(buttons[x]);
buttonNumbers.add(new Integer(x+1));
}
reset();
JFrame frame = new JFrame();
frame.getContentPane().add(statusLabel,BorderLayout.NORTH);
frame.getContentPane().add(buttonPanel,BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public void reset(){
Collections.shuffle(buttonNumbers);
for(int x = 0, y = ROWS*COLUMNS; x < y; x++){
buttons[x].setText(String.valueOf(buttonNumbers.get(x)));
}
buttonCounter = 1;
statusLabel.setText("what is 0+ 1 " + buttonCounter);
}
public static void main(String[] args) {
new NewClass();
}
}
class ButtonListener implements ActionListener {
NewClass gui;
ButtonListener(NewClass g){
gui = g;
}
public void actionPerformed(ActionEvent e) {
JButton buttonClicked = (JButton)e.getSource();
int clickedNumber = Integer.parseInt(buttonClicked.getText());
if(clickedNumber == gui.buttonCounter){
gui.buttonCounter++;
buttonClicked.setText("");//optional - clears correct selection
if(gui.buttonCounter > gui.ROWS*gui.COLUMNS) gui.reset();
gui.statusLabel.setText("what is 0+ 1" + gui.buttonCounter);
}
else {
gui.reset();
gui.statusLabel.setText("Incorrect button clicked, start again: what is 0+ 1");
}
}
}
答案 0 :(得分:1)
更改动作侦听器中的一行代码。改变这个:
gui.statusLabel.setText("what is 0+ 1" + gui.buttonCounter);
到此:
gui.statusLabel.setText("what is " + gui.buttonCounter + "+ 1");
现在它会问:
什么是3 + 1
..........................................
< / LI>