A
A
Alexiuscrow2014-08-17 23:23:03
Java
Alexiuscrow, 2014-08-17 23:23:03

Using Threads in Swing?

Now I'm trying to deal with multithreading in swing.

For example, there is a window in which there is a button, by clicking on which some long-term action-A is performed. In order for the GUI not to freeze, I decided to run the same action-A in a new thread.
e7gpc1.jpg
It looks like this:

The code
package swing.aug17_2;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;

public class SwingApp2 {

  private JFrame frame;
  private JButton btn;
  
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable(){
      public void run(){
        try {
          SwingApp2 app = new SwingApp2();
          app.frame.setVisible(true);
        } catch (Exception e){
          e.printStackTrace();
        }
      }
    });
  }
  
  public SwingApp2(){
    initialize();
  }

  private void initialize() {
    frame = new JFrame();
    frame.setTitle("Hello Swing");
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setPreferredSize(new Dimension(300, 80));
    frame.setSize(300, 80);
    frame.setLocationRelativeTo(null);
    frame.setIconImage(Toolkit.getDefaultToolkit().getImage(SwingApp2.class.getResource("/icon.png")));
    frame.getContentPane().setLayout(new BorderLayout());
    
    btn = new JButton("PUSH");
    btn.addActionListener(new ActionListener() {
      
      public void actionPerformed(ActionEvent e) {
        Thread thr = new Thread(){
          @Override
          public void run(){
            try {
              Thread.sleep(2000);
              System.out.println("Done");
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
            
          }
        };
        thr.start();
        
      }
    });
    frame.add(btn, BorderLayout.CENTER);		
  }
}

There are doubts about calling action-A in a new thread. Is it correct to call in this way? If not, please suggest the right way.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FoxInSox, 2014-08-18
@FoxInSox

All OK, do not hesitate.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question