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

  • SEARCH
  • Home
  • 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 5979183
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T21:37:24+00:00 2026-05-22T21:37:24+00:00

As many of you may know, when you have a while loop (or any

  • 0

As many of you may know, when you have a while loop (or any loop for that matter) when an input method is called, the program stops and waits for input.

e.g.

  while {
      String input = in.readLine();
      int x = 55;  //This will not execute until input has been given a value
      System.out.println (x + x);
      }

Now I am using buttons for input. Is there any way I can do the same thing (halt the program in a loop) with the use of JButton, JPanel, JFrame etc. ?

NOTE: I am also open to use the Runnable () interface if required.

UPDATE:
I am using listeners for the button. This is the exact problem.

 public void actionPerformed (ActionEvent x){ string = x.getActionCommand}

 public void someOtherMethod ()
 {

 while (true){
 start ();
 if (string.equals ("exit") break;  // This line will never execute because start() 
    //is always repeating itself.
     }
 }

EDIT:
I found a solution (FINALLY!)

this is all that needs to be done….

 string = "";
 while (true){
 if (string.equals ("");
 start ();
 if (string.equals ("exit") break; // I guess I didn't explain the problem too well...
     }

Thank you for everybody’s help!

  • 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-05-22T21:37:25+00:00Added an answer on May 22, 2026 at 9:37 pm

    I think the problem you’re having is how to change what the button does depending on what has been entered into the GUI. Remember that with a GUI, the user can interact with any enabled GUI component at any time and in any order. The key is to check the state of the GUI in your button’s ActionListener and then altering the behavior of this method depending on this GUI’s state. For example if your GUI had three JTextFields, field1, field2, and sumField and a JButton addButton:

       private JTextField field1 = new JTextField(5);
       private JTextField field2 = new JTextField(5);
       private JTextField sumField = new JTextField(5);
       private JButton addButton = new JButton("Add");
    

    And you wanted the addButton to add the numbers in field1 and field2 together and place the results into the sumField, you’re obviously not going to want to do any addition if either field is left blank, and so you test for it in the JButton’s ActionListener:

      addButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            String text1 = field1.getText().trim();
            String text2 = field2.getText().trim();
    
            if (text1.isEmpty() || text2.isEmpty()) {
               // data not entered... so return the method and do nothing
               return;
            }
    
            // if we've reached this point, the user has entered in text and so we handle it
    

    Here’s the whole thing:

    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    
    public class WaitForInput extends JPanel {
       private JTextField field1 = new JTextField(5);
       private JTextField field2 = new JTextField(5);
       private JTextField sumField = new JTextField(5);
       private JButton addButton = new JButton("Add");
    
       public WaitForInput() {
          addButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                String text1 = field1.getText().trim();
                String text2 = field2.getText().trim();
    
                if (text1.isEmpty() || text2.isEmpty()) {
                   // data not entered... so return the method and do nothing
                   return;
                }
    
                try {
                   int number1 = Integer.parseInt(field1.getText());
                   int number2 = Integer.parseInt(field2.getText());
                   int sum = number1 + number2;
    
                   sumField.setText("" + sum);
                } catch (NumberFormatException e1) {
                   // TODO: use JOptionPane to send error message
    
                   // clear the fields
                   field1.setText("");
                   field2.setText("");
                }
             }
          });
    
          add(field1);
          add(new JLabel("+"));
          add(field2);
          add(new JLabel("="));
          add(sumField);
          add(addButton);
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("WaitForInput");
          frame.getContentPane().add(new WaitForInput());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    

    EDIT 1
    Otherwise if you absolutely have to use a loop, then yes, do it in a Runnable and do that in a background Thread. Remember to call Thread.sleep(…) inside of the loop even for a short bit so it doesn’t hog the CPU. For example

    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    
    import javax.swing.*;
    
    public class HaltingProblem extends JPanel {
       private static final int PANEL_HEIGHT = 400;
       private static final int PANEL_WIDTH = 600;
       private static final long SLEEP_DELAY = 100;
       private Color[] colors = {Color.red, Color.orange, Color.yellow,
          Color.green, Color.blue, Color.cyan};
       private boolean halt = false;
       private JButton haltButton = new JButton("Halt");
       private int colorIndex = 0;
    
       public HaltingProblem() {
          setBackground(colors[colorIndex]);
          haltButton.addActionListener(new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                halt = !halt; // toggle it!
             }
          });
          add(haltButton);
    
          new Thread(new Runnable() {
             public void run() {
                while (true) {
                   keepDoingThis();
                }
             }
          }).start();
       }
    
       private void keepDoingThis() {
          try {
             Thread.sleep(SLEEP_DELAY);
          } catch (InterruptedException e) {}
    
          if (halt) {
             return;
          }
          colorIndex++;
          colorIndex %= colors.length;
          SwingUtilities.invokeLater(new Runnable() {
             public void run() {
                setBackground(colors[colorIndex]);
             }
          });
       }
    
       @Override
       public Dimension getPreferredSize() {
          return new Dimension(PANEL_WIDTH, PANEL_HEIGHT);
       }
    
       private static void createAndShowUI() {
          JFrame frame = new JFrame("HaltingProblem");
          frame.getContentPane().add(new HaltingProblem());
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.pack();
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
       }
    
       public static void main(String[] args) {
          java.awt.EventQueue.invokeLater(new Runnable() {
             public void run() {
                createAndShowUI();
             }
          });
       }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some complex stored procedures that may return many thousands of rows, and
I know that many people, at a first glance of the question, may immediately
I have 3 tables (archive has many sections, section (may) belong to many archives):
Many times I have seen Visual Studio solutions which have multiple projects that share
Many applications have grids that display data from a database table one page at
I have a list called 'optionlist' which may change length from day to day,
Problem: As you may know report wizards and reports inside crystal reports have a
Now, I have a application that composed of single master and many workers. The
I'm still learning c++ and have a question that may be obvious, or maybe
Ctrl-Shift-B, by default, builds an entire solution. An entire solution may contain many projects.

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.