如何暂停程序直到按下按钮?

我使用从jframe扩展的类,它有一个按钮(我在我的程序中使用它)

我想在我的程序中运行jframe时整个程序暂停

直到我按下按钮。

我该怎么做

在c ++ getch()这样做。

我想要一个像这样的function。

暂停执行与睡眠 ,虽然我怀疑这是你想要使用的机制。 因此,正如其他人所建议的那样,我相信您需要实现wait-notify逻辑。 这是一个非常人为的例子:

 import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.concurrent.atomic.AtomicBoolean; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; @SuppressWarnings("serial") public class PanelWithButton extends JPanel { // Field members private AtomicBoolean paused; private JTextArea textArea; private JButton button; private Thread threadObject; /** * Constructor */ public PanelWithButton() { paused = new AtomicBoolean(false); textArea = new JTextArea(5, 30); button = new JButton(); initComponents(); } /** * Initializes components */ public void initComponents() { // Construct components textArea.setLineWrap(true); textArea.setWrapStyleWord(true); add( new JScrollPane(textArea)); button.setPreferredSize(new Dimension(100, 100)); button.setText("Pause"); button.addActionListener(new ButtonListener()); add(button); // Runnable that continually writes to text area Runnable runnable = new Runnable() { @Override public void run() { while(true) { for(int i = 0; i < Integer.MAX_VALUE; i++) { if(paused.get()) { synchronized(threadObject) { // Pause try { threadObject.wait(); } catch (InterruptedException e) { } } } // Write to text area textArea.append(Integer.toString(i) + ", "); // Sleep try { Thread.sleep(500); } catch (InterruptedException e) { } } } } }; threadObject = new Thread(runnable); threadObject.start(); } @Override public Dimension getPreferredSize() { return new Dimension(400, 200); } /** * Button action listener * @author meherts * */ class ButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent evt) { if(!paused.get()) { button.setText("Start"); paused.set(true); } else { button.setText("Pause"); paused.set(false); // Resume synchronized(threadObject) { threadObject.notify(); } } } } } 

这是你的主要课程:

  import javax.swing.JFrame; import javax.swing.SwingUtilities; public class MainClass { /** * Main method of this application */ public static void main(final String[] arg) { SwingUtilities.invokeLater(new Runnable() { public void run() { JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new PanelWithButton()); frame.pack(); frame.setVisible(true); frame.setLocationRelativeTo(null); } }); } } 

正如您所看到的,此示例应用程序将不断写入文本区域,直到您单击“暂停”按钮,然后恢复您需要单击同一按钮,该按钮现在将显示为“开始”。

这个答案完全取决于我是否正确理解您的问题,如果您想要更好的答案,请提供更多信息。 开始:

在循环场景中暂停

  boolean paused; while(true ) { if(paused) { Thread.sleep(1000); // or do whatever you want in the paused state } else { doTask1 doTask2 doTask3 } } 

线程:您也可以将这些任务放入单独的线程而不是GUI线程,这通常是您长时间运行的操作。

暂停线程非常容易。 只需在其上调用suspend()即可。 当您要取消暂停呼叫resume()时。 然而,这些方法很危险,已被弃用。 通过检查暂停标志,更好或更安全的方式与上述类似。这是我在我的片段中躺着的一个简短示例。 不能完全记住我在哪里得到它:

 // Create and start the thread MyThread thread = new MyThread(); thread.start(); while (true) { // Do work // Pause the thread synchronized (thread) { thread.pleaseWait = true; } // Do work // Resume the thread synchronized (thread) { thread.pleaseWait = false; thread.notify(); } // Do work } class MyThread extends Thread { boolean pleaseWait = false; // This method is called when the thread runs public void run() { while (true) { // Do work // Check if should wait synchronized (this) { while (pleaseWait) { try { wait(); } catch (Exception e) { } } } // Do work } } } // Create and start the thread MyThread thread = new MyThread(); thread.start(); while (true) { // Do work // Pause the thread synchronized (thread) { thread.pleaseWait = true; } // Do work // Resume the thread synchronized (thread) { thread.pleaseWait = false; thread.notify(); } // Do work } class MyThread extends Thread { boolean pleaseWait = false; // This method is called when the thread runs public void run() { while (true) { // Do work // Check if should wait synchronized (this) { while (pleaseWait) { try { wait(); } catch (Exception e) { } } } // Do work } } } 

希望这可以帮助

试试我的java暂停按钮:

 package drawFramePackage; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JFrame; import javax.swing.Timer; public class Milliseconds2 implements ActionListener, MouseListener{ JFrame j; Timer t; Integer onesAndZeros, time, time2, placeHolder2; Boolean hasFired; /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub new Milliseconds2(); } public Milliseconds2(){ j = new JFrame(); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); j.setSize(new Dimension(300, 300)); j.setVisible(true); j.addMouseListener(this); onesAndZeros = new Integer(0); time = new Integer(0); time2 = new Integer(0); placeHolder2 = new Integer(0); hasFired = new Boolean(true); t = new Timer(2400, this); time = (int) System.currentTimeMillis(); t.start(); } @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub if (onesAndZeros.equals(0)){ t.stop(); if (hasFired){ time2 = t.getDelay() - ((int) System.currentTimeMillis() - time); } else{ time2 -= (int) System.currentTimeMillis() - placeHolder2; } if (hasFired){ hasFired = false; } onesAndZeros = -1; } if (onesAndZeros.equals(1)){ //System.out.println(time2); t.setInitialDelay(time2); t.start(); placeHolder2 = (int) System.currentTimeMillis(); onesAndZeros = 0; } if (onesAndZeros.equals(-1)){ onesAndZeros = 1; } } @Override public void mousePressed(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent e) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent e) { // TODO Auto-generated method stub } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub time = (int) System.currentTimeMillis(); hasFired = true; System.out.println("Message"); } } 

冻结你的主线程将有效地冻结整个程序,并可能导致操作系统认为应用程序已崩溃,不太确定,如果我错了,请纠正我。 您可以尝试隐藏/禁用控件,并在用户单击按钮时再次启用它们。

暂停时你没有说出你的意思。 你的应用在做什么?

根据经验,您不能暂停UI应用程序。 用户界面应用程序从消息处理循环运行。 消息进入,消息被调度,循环等待另一条消息。 应用程序仍然需要处理诸如用户单击按钮,调整窗口大小,关闭应用程序等操作,以便此循环连续运行。

如果你希望你的应用程序在阻止用户做某事的意义上“暂停”,那么只要使用不希望用户做的任何按钮或菜单变灰。

如果你的应用程序在后台运行一个线程,并希望它在你恢复之前暂停该操作,那么你可以很容易地这样做。

 MyThread mythread = new MyThread(); // Main thread void pause() { mythread.pause = true; } void resume() { synchronized (mythread) { mythread.pause = false; mythread.notify(); } } class MyThread extends Thread { public boolean pause = false; public void run() { while (someCondition) { synchronized (this) { if (pause) { wait(); } } doSomething(); } } } 

也可以使用Thread.suspend(),Thread.resume()来完成类似的操作,但这些本身就很危险,因为当你挂起它时你不知道线程在哪里。 它可以打开一个文件,通过套接字发送消息的一半等。在任何循环控制你的线程中进行测试允许你在安全的时候暂停。

UI使用消息驱动机制执行任务。

如果UI中有一个按钮,并且想要在按下该按钮时运行某些按钮,则应该在按钮中添加一个ActionListener对象。 按下按钮后,它会触发ActionListener对象以执行任务,例如:

 button.addActionListener(new ActionListener { @Override public void actionPerformed(ActionEvent e) { // do something } }); 

如果你想在按下暂停按钮时停止某些东西,你将无需一个Thread 。 这比前一种情况更复杂。