"kann" javax.swing.jbutton.addactionListener (java.awt.event.ActionListener) nicht aufrufen. Richtig. < /p>
Hier ist der Code: < /p>
Code: Select all
import javax.swing.*;
import javax.swing.text.NumberFormatter;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.Random;
class GuessNumberGUI extends JFrame {
// Add required fields here
Random rand = new Random();
int genNo = rand.nextInt(100) +1;
int guesses = 1;
int pInput;
JLabel heading;
JTextField playerGuess;
JLabel output = new JLabel("Hint's appear here!", SwingConstants.CENTER);
JPanel panel;
JButton check;
public static void main(String[] args) {
new GuessNumberGUI();
}
public GuessNumberGUI() {
setTitle("Guess a Number") ;
setSize(400, 200); // You can change the size if you wish to
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(null);
//=======================================================
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
panel.setBackground(Color.BLACK);
//=======================================================
JLabel heading = new JLabel("Guess a Number between 1 and 100", SwingConstants.CENTER);
heading.setForeground(Color.WHITE);
heading.setFont(new Font("Arial", Font.BOLD, 20));
panel.add(heading, BorderLayout.NORTH);
//========================================================
JTextField playerGuess = new JTextField(SwingConstants.CENTER);
panel.add(playerGuess, BorderLayout.CENTER);
playerGuess.setBackground(Color.BLACK);
playerGuess.setForeground(Color.WHITE);
playerGuess.setFont(new Font("Arial", Font.BOLD, 20));
//=========================================================
JButton check = new JButton("check");
check.setFont(new Font("Arial", Font.BOLD, 20));
panel.add(check, BorderLayout.EAST);
check.setBackground(Color.BLACK);
check.setForeground(Color.WHITE);
System.out.println(genNo);
//==========================================================
output.setForeground(Color.WHITE);
output.setFont(new Font("Arial", Font.BOLD, 20));
panel.add(output, BorderLayout.SOUTH);
add(panel);
check.addActionListener(e -> {
pInput = Integer.parseInt(playerGuess.getText());
checkGuess();});
setVisible(true);
}
public void pressedCheck() {
check.addActionListener(e -> {
pInput = Integer.parseInt(playerGuess.getText());
checkGuess();});
}
public void checkGuess(){
if (pInput == genNo) {
output.setText("You guessed correctly! No. of tries:" + guesses);
}
else {
wrongGuess();
}
}
private void wrongGuess(){
while (genNo != pInput) {
if (pInput < genNo) {
tooLow();
}
else if (pInput > genNo) {
tooHigh();
}
}
}
private void tooLow(){
output.setText("Too low! Try again!");
guesses++;
pressedCheck();
}
private void tooHigh(){
output.setText("Too high! Try again!");
guesses++;
pressedCheck();
}
}
Mobile version