Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // school work
- import java.awt.*; //using awt's layouts
- import java.awt.event.*; //using awt's event classes and listener interfaces
- import javax.swing.*; //using swing's components and container
- //a swing application extends from javax.swing.JFrame
- public class SwingNumberGuess extends JFrame {
- private JTextField tfNumber, tfGuess;
- private JButton btnGenerate;
- private double number;
- private float guess;
- private Label responseLabel;
- // Constructor to set up UI components and event handlers
- public SwingNumberGuess() {
- // Swing components should be added to the content-pane of the JFrame.
- Container cp = getContentPane();
- // Set this Container to grid layout of 2 rows and 1 columns
- cp.setLayout(new GridLayout(2, 1, 10, 6));
- // Components are added from left-to-right, top-to-bottom
- cp.add(new JLabel("The Number is "));
- tfNumber = new JTextField(10);
- tfNumber.setHorizontalAlignment(JTextField.RIGHT);
- cp.add(tfNumber);
- btnGenerate = new JButton("Generate");
- cp.add(btnGenerate);
- btnGenerate.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent evt) {
- number= (Math.random());
- tfNumber.setText(String.format("%.2f",number ));
- tfNumber.setText("**");
- }
- });
- cp.add(new JLabel("Enter your guess "));
- tfGuess = new JTextField(10);
- tfGuess.setHorizontalAlignment(JTextField.RIGHT);
- cp.add(tfGuess);
- responseLabel = new Label();
- responseLabel.setAlignment(Label.LEFT);
- cp.add(responseLabel);
- tfGuess.addActionListener(new ActionListener() {
- @Override
- public void actionPerformed(ActionEvent evt) {
- guess = Float.parseFloat(tfGuess.getText());
- if ( guess > number) {
- responseLabel.setText("Try Lower");
- }
- else
- if ( guess < number){
- responseLabel.setText("Try Higher");
- }
- else
- if (guess == number) {
- responseLabel.setText("You Got It");
- }
- }
- });
- setDefaultCloseOperation(EXIT_ON_CLOSE); // for the "window-close" button
- setTitle("Guess Number");
- setSize(500, 120);
- setVisible(true);
- }
- // The entry main() method
- public static void main(String[] args) {
- // For thread safety, use the event-dispatching thread to construct UI
- javax.swing.SwingUtilities.invokeLater(new Runnable() {
- @Override
- public void run() {
- new SwingNumberGuess(); // Let the constructor does the job
- }
- });
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement