开发者

how to pause program until a button press?

开发者 https://www.devze.com 2023-02-20 17:28 出处:网络
i use from a class that extended from jframe and it has a button(i use from it in my program) i want when run jframe in my program the whole of my program pause

i use from a class that extended from jframe and it has a button(i use from it in my program)

i want when run jframe in my program the whole of my program pause

until i press the button.

how can i d开发者_如何学编程o it

in c++ getch() do this.

i want a function like that.


Pausing Execution with Sleep, although I doubt that is the mechanism that you'll want to use. So, as others have suggested, I believe you'll need to implement wait-notify logic. Here's an extremely contrived example:

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

And here's your main class:

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

how to pause program until a button press?

As you can see, this example application will continually write to the text area until you click the button that reads 'Pause', whereupon to resume you'll need to click that same button which will now read 'Start'.


You don't say what you mean by pause. What is your app doing?

As a rule of thumb you CAN'T pause a UI app. User interface applications run from a message processing loop. Message comes in, message is dispatched, loop waits for another message. An app still needs to handles things like the user clicking on buttons, resizing the window, closing the app and so forth so this loop runs continuously.

If you want your application to "pause" in the sense of prevent the user doing something, just grey out whatever button or menu it is you don't want users to be doing.

If your app is running a thread in the background and wish it to suspend that action until you resume it, you can do so fairly easily like this.

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

It is also possible to use Thread.suspend(), Thread.resume() to accomplish similar but these are inherently dangerous because you have no idea where the thread is when you suspend it. It could have a file open, be half way through sending a message over a socket etc. Putting a test in whatever loop controls your thread allows you do suspend at a point when it is safe to do so.


This answer entirely depends on whether I understand your question correctly, please give a bit more info if you want better answers. Here goes:

Pausing in a loop scenario

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

Threads: You can also put those tasks into a seperate thread and not on the GUI thread which is typically what you would do for long running operations.

Pausing a thread is very easy. Just call suspend() on it. When you want to unpause call resume(). These methods however are dangerous and have been deprecated. Better or rather safer way to do it would be similar to the above by checking a pause flag.Here is a short example I had lying around in my snippets. Cant exactly remember where I got it in the first place:

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

Hope this helps


try my java pause button:

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


Freezing your Main Thread will effectively freeze the entire program and could cause the operating system to think the application has crashed, not quite sure so correct me if I'm wrong. You could try to hide/disable the controls and enable them again when the user clicks on your button.


UI performs task using message driven mechanism.

If you have a button in your UI and you want to run something when that button is pressed, you should add an object of ActionListener to your button. Once the button is pressed, it fires the ActionListener object to perform a task, e.g.:

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

If you want to stop something when you press a pause button, you will defnitely need a Thread. This is more complicated than the former case.

0

精彩评论

暂无评论...
验证码 换一张
取 消