I'm setting up a new program. By clicking on the start button in the program, I want to start the thread, and stop by clicking the stop button.So start button start the thread, stop button stop. How should I convert the code to work properly? I only need to use one thread.
public class server implements Runnable, ActionListener {
JFrame frame;
JButton button1;
JButton button2;
public void makeFrame() {
frame = new JFrame("Frame");
frame.setSize(1000, 500);
frame.getContentPane().setBackground(new Color(74, 74, 74));
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setLayout(null);
}
public void makeButtons() {
gomb1 = new JButton("Indítás");
gomb1.setBounds(350, 300, 100, 30);
gomb1.setBackground(new Color(127, 127, 127));
frame.getContentPane().add(gomb1);
gomb1.addActionListener(this);
gomb2 = new JButton("Stop");
gomb2.setBounds(550, 300, 100, 30);
gomb2.setBackground(new Color(127, 127, 127));
frame.getContentPane().add(gomb2);
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == button1) {
}
}
@Override
public void run() {
try {
go();
} catch (InterruptedException ex) {
Logger.getLogger(server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void go() throws InterruptedException {
doMore();
}
public void doMore() throws InterruptedException {
for (int i = 0; i < 20; i++) {
System.out.println("Fut a thread" + i);
}
}
}
class Test {
public static void main(String[] args) {
server t = new server();
t.makeFrame();
t.makeButtons();
Runnable r = new server();
Thread szal = new Thread(r);
Thread szal2 = new Thread(r);
szal.start();
szal2.start();
}
}