Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.EventQueue;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.util.Random;
- import javax.swing.JButton;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- import javax.swing.JTextField;
- public class Frame01 {
- private Random ran = new Random();
- private int Low = 1;
- private int High = 50;
- private int Result = ran.nextInt(High-Low) + Low;
- private JFrame frame;
- public static void main(String[] args) {
- EventQueue.invokeLater(new Runnable() {
- public void run() {
- try {
- Frame01 window = new Frame01();
- window.frame.setVisible(true);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- });
- }
- /**
- * Create the application.
- */
- public Frame01() {
- initialize();
- }
- /**
- * Initialize the contents of the frame.
- */
- public void initialize() {
- frame = new JFrame();
- frame.setBounds(100, 100, 450, 300);
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- // This is a label where we will put our answer
- JLabel lab = new JLabel();
- lab.setBounds(131, 6, 185, 30);
- lab.setText("Enter a number!");
- frame.getContentPane().setLayout(null);
- frame.getContentPane().add(lab);
- frame.setResizable(false);
- // Now Let's add the TextField where the player will enter is answer.
- JTextField txtfield = new JTextField();
- txtfield.setBounds(131, 63, 168, 39);
- frame.getContentPane().add(txtfield);
- txtfield.setColumns(10);
- //This line mean the action when the TextField Get Input
- txtfield.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- // Convert our Int into a String
- StringBuilder sb = new StringBuilder();
- sb.append("");
- sb.append(Result);
- String rslt = sb.toString();
- // Action Line Here
- // String to get the value of the TextField
- String txt = txtfield.getText();
- // We use the method "If" to compare the result with the answer of the player.
- if(txt.equals(rslt)){
- lab.setText("You win the game!");
- frame.setTitle("You win!");
- }else if(!(txt.equals(rslt))){
- lab.setText("Try again!");
- frame.setTitle("Try Again!");
- }
- }
- });
- // This line is to explain the rules of the game
- JLabel lab2 = new JLabel();
- lab2.setBounds(120, 250, 250, 30);
- lab2.setText("The aswer in between 1 and 50");
- frame.getContentPane().setLayout(null);
- frame.getContentPane().add(lab2);
- StringBuilder sb = new StringBuilder();
- sb.append("");
- sb.append(Result);
- String rslt = sb.toString();
- JButton btn = new JButton("Hint");
- btn.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- JOptionPane.showMessageDialog(frame, rslt);
- }
- });
- btn.setBounds(10, 250, 70, 30);
- frame.getContentPane().add(btn);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement