Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8884127
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T20:59:21+00:00 2026-06-14T20:59:21+00:00

I’ve hit the infinite loop problem in Swing. Done some research and come across

  • 0

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);
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T20:59:22+00:00Added an answer on June 14, 2026 at 8:59 pm

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all’Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
For some reason, after submitting a string like this Jack’s Spindle from a text
Seemingly simple, but I cannot find anything relevant on the web. What is the
I am currently running into a problem where an element is coming back from
I have a French site that I want to parse, but am running into
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
This could be a duplicate question, but I have no idea what search terms

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.