1

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();
    }
}
rdas
  • 20,604
  • 6
  • 33
  • 46
yajdem
  • 11
  • 1
  • https://stackoverflow.com/questions/3194545/how-to-stop-a-java-thread-gracefully – rdas May 01 '19 at 09:37
  • to start and stop a thread - this is a wrong desire. Try to formulate it differently. Start with more general description - you want some work to be done or not, some picture change or not etc. – Alexei Kaigorodov May 02 '19 at 12:33

0 Answers0