Translate

Random Number Game Code





package javaapplication4;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.math.*;
import java.lang.*;
public class JavaApplication4 extends JFrame
{
private  JLabel label;
private JLabel l;

private JLabel l2;
private JButton button;
private JButton b;
private JTextField text1;
private JTextField text2;

private int x;
private int guess;
public JavaApplication4()
  {
   setLayout(new FlowLayout());

 
   label = new JLabel("Random Number Game");
  add(label);
 
  l = new JLabel("Your Number(1-10)");
  add(l);
 
  text1 = new JTextField(10);
  add(text1);
 
  text2 = new JTextField(10);
  add(text2);
  button = new JButton("Guess");
  add(button);
 
  l2 = new JLabel("");
  add(l2);
 
  event e  = new event();
//Every Element involved in the event must be registered.
 
button.addActionListener(e);
 }

    public class event implements ActionListener
    {
    public void actionPerformed(ActionEvent e)
    {
    guess =(int)(Double.parseDouble(text1.getText()));   
   
    if(button.hasFocus())
    {   
    x=(int)(Math.random()*10+1);
    if(guess == x)
    {
    l2.setText("You Win!");
    text2.setText("Number is "+x);
    }
    else
    {
    l2.setText("You Lose!");
    text2.setText("Number is "+x);
    }
    }
    }
   
    }
   
   
    public static void main(String[] args) {
        JavaApplication4 gui = new JavaApplication4();
       gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        gui.setTitle("Event Window");
        gui.setVisible(true);
        gui.setSize(175, 200);
    }
   
}
Previous
Next Post »

Contact Form

Name

Email *

Message *