Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package stackoverflowtests;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.SwingConstants;
- import java.awt.Font;
- import javax.swing.JTextField;
- import java.awt.Color;
- import java.awt.Dimension;
- import javax.swing.JButton;
- import java.awt.event.ActionListener;
- import java.awt.event.ActionEvent;
- public class GuessingGame extends JFrame {
- private static final long serialVersionUID = 1L;
- private JLabel lblOutput;
- private int theNumber;
- private JTextField txtGuess;
- public void checkGuess() {
- String guessText = txtGuess.getText();
- txtGuess.setText("");//Empties the contents of the text field.
- String message = "";
- int guess = Integer.parseInt(guessText);
- if (guess < theNumber)
- message = guess + " is too low. Try again.";
- else if (guess > theNumber)
- message = guess + " is too high. Try again.";
- else {
- message = guess + " is correct. Let's play again!";
- newGame();
- }
- lblOutput.setText(message);
- }
- public void newGame() {
- theNumber = (int) (Math.random() * 100 + 1);
- }
- public GuessingGame() {
- setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- setTitle("Tim's Hi-Lo Guessing Game");
- getContentPane().setLayout(null);
- JLabel lblNewLabel = new JLabel("Tim's Hi-Lo Guessing Game");
- lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 15));
- lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
- lblNewLabel.setBounds(0, 10, 436, 32);
- getContentPane().add(lblNewLabel);
- JLabel lblNewLabel_1 = new JLabel("Guess a number between 1 and 100:");
- lblNewLabel_1.setBackground(new Color(240, 240, 240));
- lblNewLabel_1.setHorizontalAlignment(SwingConstants.RIGHT);
- lblNewLabel_1.setBounds(147, 54, 215, 13);
- getContentPane().add(lblNewLabel_1);
- txtGuess = new JTextField();
- txtGuess.addActionListener((ActionEvent e) -> {
- checkGuess();
- });
- txtGuess.setHorizontalAlignment(SwingConstants.RIGHT);
- txtGuess.setBounds(260, 122, 27, 19);
- getContentPane().add(txtGuess);
- txtGuess.setColumns(10);
- JButton btnGuess = new JButton("Guess!");
- btnGuess.addActionListener((ActionEvent e) -> {
- checkGuess();
- });
- btnGuess.setBounds(172, 121, 85, 21);
- getContentPane().add(btnGuess);
- lblOutput = new JLabel("Enter a number above and click Guess!");
- lblOutput.setHorizontalAlignment(SwingConstants.CENTER);
- lblOutput.setBounds(58, 196, 350, 13);
- getContentPane().add(lblOutput);
- }
- public static void main(String[] args) {
- GuessingGame theGame = new GuessingGame();
- theGame.newGame();
- theGame.setSize(new Dimension(450, 300));
- theGame.setVisible(true);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement