创建一个Java窗体,并不使用封装,在文本框中可以进行一个随机数猜数程序,猜错就提示猜大或者猜小,当猜对时,在文本框中显示猜对了,并在窗体下方显示一张图片
时间: 2023-12-03 08:03:45 浏览: 84
好的,我可以为您提供该程序的代码。请注意,这段代码是使用Java Swing编写的,不使用封装。
```java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GuessNumber extends JFrame {
private int randomNumber;
private int guessesLeft;
private JTextField guessTextField;
private JTextArea resultTextArea;
private JLabel imageLabel;
public GuessNumber() {
super("Guess Number Game");
randomNumber = (int) (Math.random() * 100) + 1;
guessesLeft = 10;
JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
JPanel topPanel = new JPanel();
topPanel.setLayout(new FlowLayout());
topPanel.add(new JLabel("Guess a number between 1 and 100: "));
guessTextField = new JTextField(10);
topPanel.add(guessTextField);
JButton guessButton = new JButton("Guess");
guessButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String guessString = guessTextField.getText();
if (guessString.matches("\\d+")) {
int guess = Integer.parseInt(guessString);
if (guess >= 1 && guess <= 100) {
guessesLeft--;
if (guess == randomNumber) {
resultTextArea.setText("Congratulations! You guessed the number.");
imageLabel.setIcon(new ImageIcon("congratulations.png"));
guessTextField.setEnabled(false);
} else if (guessesLeft == 0) {
resultTextArea.setText("Sorry, you did not guess the number. The number was " + randomNumber + ".");
imageLabel.setIcon(new ImageIcon("gameover.png"));
guessTextField.setEnabled(false);
} else if (guess < randomNumber) {
resultTextArea.append("Your guess was too low. You have " + guessesLeft + " guesses left.\n");
} else {
resultTextArea.append("Your guess was too high. You have " + guessesLeft + " guesses left.\n");
}
} else {
JOptionPane.showMessageDialog(GuessNumber.this, "Please enter a number between 1 and 100.");
}
} else {
JOptionPane.showMessageDialog(GuessNumber.this, "Please enter a valid number.");
}
guessTextField.setText("");
guessTextField.requestFocus();
}
});
topPanel.add(guessButton);
mainPanel.add(topPanel, BorderLayout.NORTH);
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout());
resultTextArea = new JTextArea(5, 20);
centerPanel.add(new JScrollPane(resultTextArea), BorderLayout.CENTER);
mainPanel.add(centerPanel, BorderLayout.CENTER);
imageLabel = new JLabel();
mainPanel.add(imageLabel, BorderLayout.SOUTH);
add(mainPanel);
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new GuessNumber();
}
}
```
请注意,该程序有两张图片(“congratulations.png”和“gameover.png”),您需要将它们放在与程序相同的目录中。这些图片可以是任何您喜欢的东西,只需将它们命名为“congratulations.png”和“gameover.png”。
希望这个程序对您有所帮助!
阅读全文