Ho appena iniziato ad apprendere la GUI Java e ho affrontato questo problema mentre praticavo la gestione degli eventi. Here's the initial windowCosa c'è di sbagliato con questo codice di Java GUI?
Quando inserisco un numero all'interno del campo di testo, è necessario dire se il numero indovinato è più alto, più basso o abbinato. Se non corrisponde, richiederebbe un altro numero. Ma la finestra si blocca appena. After entering data
Immagino che cada in un ciclo infinito. Ecco il codice. Aiutami a capire dove si trova il problema. Grazie.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class RandomNumGame extends JFrame {
private JLabel promptLabel, resultLabel, answerLabel;
private int tries=1, randomNum, guessNum;
private JButton button;
private JTextField txt;
private boolean guessed;
public RandomNumGame() {
setLayout(new FlowLayout());
promptLabel = new JLabel("Guess a number(1-1000): ");
add(promptLabel);
txt = new JTextField(7);
add(txt);
button = new JButton("Guess!");
add(button);
resultLabel = new JLabel("");
add(resultLabel);
/*answerLabel = new JLabel("");
add(answerLabel);
*/
Event e = new Event();
button.addActionListener(e);
}
private class Event implements ActionListener{
public void actionPerformed(ActionEvent e){
randomNum = (int)(Math.random() * 1000 + 1);
guessed=false;
do{
try{
guessNum = (int)(Double.parseDouble(txt.getText()));
if(guessNum>randomNum){
resultLabel.setText("Your number is higher. Try Again");
}
else if(guessNum<randomNum){
resultLabel.setText("Your number is lower. Try Again");
}
else{
resultLabel.setText("Your number matched!");
guessed=true;
}
}
catch(Exception ee){
resultLabel.setText("Enter a legit number. What are you stupid?");
}
}while(!guessed);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
RandomNumGame ran = new RandomNumGame();
ran.setDefaultCloseOperation(EXIT_ON_CLOSE);
ran.setSize(300, 120);
//ran.pack();
ran.setVisible(true);
ran.setTitle("Random Number Game");
}
}
Grazie mille. Questo ha fatto il trucco. –