Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Swing cancelling an Infinite loop

Tags:

java

swing

I've hit the infinite loop problem in Swing. Done some research and come across SwingWorker threads but not really sure how to implement them. I've knocked together a simple program that shows the problem. One button starts the infinite loop and I want the other button to stop it but of course due to the Swing single thread problem the other button has frozen. Code below and help appreciated:-

public class Model
{
    private int counter;
    private boolean go = true;

    public void go()
    {
        counter = 0;

        while(go)
        {
            counter++;
            System.out.println(counter);
        }
    }

    public int getCounter()
    {
        return counter;
    }

    public void setGo(boolean value)
    {
        this.go = value;
    }
}

public class View extends JFrame
{
    private JPanel                  topPanel, bottomPanel;
    private JTextArea               messageArea;
    private JButton                 startButton, cancelButton;
    private JLabel                  messageLabel;
    private JScrollPane             scrollPane;

    public View()
    {
        setSize(250, 220);
        setTitle("View");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        topPanel = new JPanel();
        bottomPanel = new JPanel();
        messageArea = new JTextArea(8, 20);
        messageArea.setEditable(false);
        scrollPane = new JScrollPane(messageArea);
        messageLabel = new JLabel("Message Area");
        topPanel.setLayout(new BorderLayout());
        topPanel.add(messageLabel, "North");
        topPanel.add(scrollPane, "South");
        startButton = new JButton("START");
        cancelButton = new JButton("CANCEL");
        bottomPanel.setLayout(new GridLayout(1, 2));
        bottomPanel.add(startButton);
        bottomPanel.add(cancelButton);
        Container cp = getContentPane();
        cp.add(topPanel, BorderLayout.NORTH);
        cp.add(bottomPanel, BorderLayout.SOUTH);
    }

    public JButton getStartButton()
    {
        return startButton;
    }

    public JButton getCancelButton()
    {
        return cancelButton;
    }

    public void setMessageArea(String message)
    {
        messageArea.append(message + "\n");
    }
}


public class Controller implements ActionListener
{
    private Model theModel;
    private View  theView;

    public Controller(Model model, View view)
    {
        this.theModel = model;
        this.theView = view;
        view.getStartButton().addActionListener(this);
        view.getCancelButton().addActionListener(this);
    }

    public void actionPerformed(ActionEvent ae)
    {
        Object buttonClicked = ae.getSource();
        if(buttonClicked.equals(theView.getStartButton()))
        {
            theModel.go();
        }
        else if(buttonClicked.equals(theView.getCancelButton()))
        {
            theModel.setGo(false);
        }
    }
}



public class Main
{
    public static void main(String[] args)
    {
        Model model = new Model();
        View view = new View();
        Controller controller = new Controller(model, view);
        view.setVisible(true);
    }
}
like image 341
Paul Avatar asked Jan 16 '23 01:01

Paul


1 Answers

You can do it easily without implementing any timer, you just need to add two lines to your actionPerformed method:

public void actionPerformed(ActionEvent ae)
{
    Object buttonClicked = ae.getSource();
    if(buttonClicked.equals(theView.getStartButton()))
    {
      theModel.setGo(true); //make it continue if it's just stopped
      Thread t = new Thread(new Runnable() { public void run() {theModel.go();}}); //This separate thread will start the new go...
      t.start(); //...when you start the thread! go!
    }
    else if(buttonClicked.equals(theView.getCancelButton()))
    {
        theModel.setGo(false);
    }
}

As your Model.go() is running in a separate thread, the Event Dispatch Thread is free to do its stuff, like drawing the button released again, instead of hanging with the button down.

There's a catch! however, because the thread running Model.go() will run wildly!, it's virtually called as many times per second as your system can.

If you plan to implement some animation or the like, then you will need to:

  • use a Timer,

or

  • add some sleep time to the new thread.

Example if you go with threads:

public void go()
{
    counter = 0;
        while(go)
    {
        counter++;
        System.out.println(counter);
        try {
            Thread.sleep(1500); //Sleep for 1.5 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

As you can see I added Thread.sleep(1500) being 1500 the time in milliseconds (1.5 seconds). Thread.sleep can be interrupted for some reasons, so you must catch the InterruptedException.

It's not necessary to go deeper on handling correctly the InterruptedException in this particular case, but if you feel curious about it you can read this nice article.

like image 200
マルちゃん だよ Avatar answered Jan 25 '23 03:01

マルちゃん だよ