Slip No 7 Q B

Write a Multithreading program in java to display the number’s between 1 to 100 continuously in a TextField by clicking on button.

NumberDisplay.java

import java.awt.*;
import java.awt.event.*;

public class NumberDisplay extends Frame implements ActionListener, Runnable {

    TextField tf;
    Button btn;
    Thread t;

    public NumberDisplay() {
        // Create TextField and Button
        tf = new TextField();
        btn = new Button("Start");

        // Set layout
        setLayout(new FlowLayout());

        // Add components
        add(tf);
        add(btn);

        // Button event
        btn.addActionListener(this);

        // Frame settings
        setSize(300, 150);
        setVisible(true);

        // Close window
        addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    // Button click action
    public void actionPerformed(ActionEvent e) {
        t = new Thread(this);
        t.start();
    }

    // Thread execution
    public void run() {
        try {
            for (int i = 1; i <= 100; i++) {
                tf.setText(String.valueOf(i));
                Thread.sleep(200); // delay for continuous display
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    public static void main(String[] args) {
        new NumberDisplay();
    }
}
Spread the love

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top