Write a Java program Design a screen with two buttons start thread and stop thread. Clicking on start it should start printing "Thread running" until stop button is pressed.
Write a Java program Design a screen with two buttons start thread and stop thread. Clicking on start it should start printing "Thread running" until stop button is pressed.
Program:
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ThreadRun extends JFrame implements Runnable, ActionListener {
int i,j;
String str, msg = "Thread running";
Thread t;
JButton btnStart, btnStop;
JPanel panel;
public ThreadRun() {
Container c = getContentPane();
setDefaultCloseOperation(EXIT_ON_CLOSE);
t = new Thread(this);
panel = new JPanel();
btnStart = new JButton("Start Thread");
btnStop = new JButton("Stop Thread");
panel.add(btnStart);
panel.add(btnStop);
btnStart.addActionListener(this);
btnStop.addActionListener(this);
c.add(panel);
setSize(500,600);
setVisible(true);
j=80;
}
public void run(){
try {
while(true){
repaint();
t.sleep(500);
}
}catch(InterruptedException e){
System.out.println(e);
}
}
public void actionPerformed(ActionEvent ae){
str = ae.getActionCommand();
if(str.equals("Start Thread")){
t.start();
} else if(str.equals("Stop Thread")){
t.stop();
}
}
public void update(Graphics g){
repaint();
}
public void paint(Graphics g){
g.drawString(msg,50,j);
j+=20;
}
public static void main(String args[]){
ThreadRun tr = new ThreadRun();
}
}
Comments
Post a Comment