|
import javax.swing. *;
import java.awt. *;
import java.awt.event. *;
import javax.swing.border. *;
import java.util. *;
class SimpleGameFrame extends JFrame {
private JLabel one;
private JLabel two;
private JLabel [] jl;
private JButton start;
private JButton output;
private JTextField input;
private int [] arry = new int [5] ;;
Ranch
SimpleGameFrame () {
this.setSize (500, 400);
this.setLocation (200, 100);
this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
this.setTitle ("Number Game");
this.addComponent ();
this.setVisible (true);
}
Ranch
private void addComponent () {
JPanel jp = (JPanel) this.getContentPane ();
jp.setLayout (null);
one = new JLabel ("Test your digital consciousness");
one.setBounds (180, 70, 180, 20);
jp.add (one);
jl = new JLabel [4];
for (int i = 0; i <jl.length; i ++) {
jl [i] = new JLabel ();
jl [i] .setBorder (new LineBorder (Color.black));
jl [i] .setBounds (60 + i * 100, 160, 90, 30);
jp.add (jl [i]);
}
two = new JLabel ("Please find the regular number and fill in the fifth number:");
two.setBounds (80, 230, 180, 20);
jp.add (two);
input = new JTextField ();
input.setBounds (260, 225, 100, 30);
jp.add (input);
start = new JButton ("Start");
start.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
setNum ();
for (int i = 0; i <jl.length; i ++) {
jl [i] .setText (String.valueOf (arry [i]));
}
input.setText ("");
input.requestFocus ();
}
});
start.setBounds (100, 300, 120, 30);
jp.add (start);
output = new JButton ("See results");
output.addActionListener (new ActionListener () {
public void actionPerformed (ActionEvent e) {
judgeRes ();
}
});
output.setBounds (260, 300, 120, 30);
jp.add (output);
}
Ranch
private void setNum () {
Random ran = new Random ();
int num = Math.abs (ran.nextInt ()% 9);
arry [0] = num;
for (int i = 1; i <arry.length; i ++) {
arry [i] = 2 * arry [i-1] +1;
}
}
Ranch
private void judgeRes () {
if (input.getText (). equals (String.valueOf (arry [4]))) {
JOptionPane.showMessageDialog (null, "Wow, you are right, you are so smart!");
} else if (input.getText (). equals ("")) {
JOptionPane.showMessageDialog (null, "You haven't filled in the answer yet!");
input.requestFocus ();
} else {
JOptionPane.showMessageDialog (null, "You are stupid, try again!");
input.setText (String.valueOf (arry [4]));
}
start.setText ("Try again");
}
} |
|