Zeveso
Zeveso

Reputation: 1294

How can I stop a Thread from GUI button?

I was wondering how it was I could stop a Thread from a GUI. I figured that if the thread was made before the buttons were made I would be fine, but I am also trying to put in the JProgressBar so that I can update it. So now I am stuck as of how to do this. If you could help that would be nice.

Thanks in advance!

Code:

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import javax.swing.JOptionPane;

public class mainJFrame extends javax.swing.JFrame {

    //set Global variables
    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    final int screenH = dim.height, screenW = dim.width;
    private volatile boolean isStop = true;

    public mainJFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")                          
    private void initComponents() {

        jProgressBar1 = new javax.swing.JProgressBar();
        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Zeveso's MD5 Cracker");
        setBounds(new java.awt.Rectangle(200, 200, 0, 0));
        setResizable(false);

        jLabel1.setText("MD5:");

        jButton1.setText("Start");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText("Stop");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jMenu1.setText("File");

        jMenuItem1.setText("Create MD5");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jProgressBar1, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 191, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addGap(18, 18, 18)
                        .addComponent(jButton2)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 29, Short.MAX_VALUE)
                .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }                    

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        if(isStop == true){
        jProgressBar1.setIndeterminate(true);
        myMDThread.start();
        isStop = false;
        }
        else{
            System.out.println("Already running!");
        }
    }                                        

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {                                           
        createMD5 myMD = new createMD5();
        String myPass = JOptionPane.showInputDialog(null, "Please put your password!");
        myPass = myMD.getMD5(myPass);
        JOptionPane.showMessageDialog(null, "MD5: " + myPass);
        System.out.println(myPass);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        StringSelection stringSelection = new StringSelection(myPass);
        clipboard.setContents(stringSelection, null);
    }                                          

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        jProgressBar1.setIndeterminate(false);
        isStop = true;
    }                                        


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new mainJFrame().setVisible(true);
            }
        });
    }                  
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JTextField jTextField1;                
}

Upvotes: 0

Views: 4940

Answers (2)

Neil Bartlett
Neil Bartlett

Reputation: 23958

There is no safe way to force a thread to stop (read the JavaDoc on the Thread.stop() method for more explanation).

The best way is to call the interrupt method, which is a "cooperative" stop. If the thread is in the middle of an interruptible call then it will throw an InterruptedException. If the thread is compute-intensive then it should periodically check its own interrupt status with Thread.interrupted(), and cleanly exit when requested.

Upvotes: 3

davetron5000
davetron5000

Reputation: 24891

Do you have the source for your thread?

In general, you cannot stop a thread unless you build in the ability to do so. For example, your thread could expose a method like stopProcessing that, when called, sets a flag. Your thread's run method would periodically check this flag to see if it should stop.

If you have a bit of work that doesn't map to this very well, your only real option is to just ignore the Thread, hide the progress bar, and give the illusion that the thread has stopped.

Upvotes: 1

Related Questions