Java:在没有输入提示的情况下停止程序

发布于 2024-11-13 12:06:45 字数 994 浏览 3 评论 0原文

正如你们中许多人可能知道的那样,当调用输入方法时有 while 循环(或任何与此相关的循环)时,程序将停止并等待输入。

例如

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

现在我使用按钮进行输入。有什么方法可以使用 JButton、JPanel、JFrame 等来做同样的事情(循环停止程序)?

注意:如果需要,我也愿意使用 Runnable () 接口。

更新: 我正在使用按钮的侦听器。这正是问题所在。

 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.
     }
 }

编辑: 我找到了一个解决方案(终于!)

这就是需要做的一切......

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

谢谢大家的帮助!

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!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

私野 2024-11-20 12:06:45

我认为您遇到的问题是如何根据 GUI 中输入的内容来更改按钮的功能。请记住,使用 GUI,用户可以随时以任何顺序与任何启用的 GUI 组件进行交互。关键是检查按钮的 ActionListener 中 GUI 的状态,然后根据此 GUI 的状态更改此方法的行为。例如,如果您的 GUI 有三个 JTextFields、field1、field2 和 sumField 以及一个 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");

并且您希望 addButton 将 field1 和 field2 中的数字相加并将结果放入 sumField,那么您显然不会想要如果任一字段留空,则进行任何添加,因此您在 JButton 的 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

这是整个事情:

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();
         }
      });
   }
}

编辑 1
否则,如果您绝对必须使用循环,那么是的,在 Runnable 中执行此操作并在后台线程中执行此操作。请记住在循环内部调用 Thread.sleep(...),即使是一小段,这样它就不会占用 CPU。例如

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();
         }
      });
   }
}

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();
         }
      });
   }
}
身边 2024-11-20 12:06:45

当您使用 GUI 时,编程范例有点不同。

通过在按钮上注册侦听器,您会在发生某些情况时收到通知 - 如果没有发生任何事情,则 Swing 事件循环 (EDT) 已经“不执行任何操作”。

也许我误解了这个问题。

The programming paradigm is a bit different when you're using a GUI.

By registering listeners on the buttons you get notified when something happens - if nothing happens the Swing event loop (EDT) is already doing "nothing".

Perhaps I misunderstood the question though.

霊感 2024-11-20 12:06:45

如果您有 GUI,则通常不会有无限执行的中央主循环。响应事件的规范方法是使用事件侦听器

mybutton.addListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) { System.out.println("Clicked"); }
    });

If you have a GUI, you do not generally have a central main loop that executes indefinitely. The canonical way to respond to events is with event listeners:

mybutton.addListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) { System.out.println("Clicked"); }
    });
平生欢 2024-11-20 12:06:45

让您的 JFrame 实现 ActionListener 并调用 button.addActionListener(this)。然后,当单击按钮时,actionPerformed(ActionEvent event) 方法中的代码将执行:)

或者您可以使 ActionListener 匿名:

button.addActionListener(new ActionListener() {
    void actionPerformed(ActionEvent event) {
        // Insert code to execute when button is clicked
    }
}

Make your JFrame implement ActionListener and call button.addActionListener(this). Then the code inside the actionPerformed(ActionEvent event) method will execute when the button is clicked :)

Or you could make the ActionListener anonymous with

button.addActionListener(new ActionListener() {
    void actionPerformed(ActionEvent event) {
        // Insert code to execute when button is clicked
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文