Tuesday, June 12, 2012

Run a JFrame application using SwingUtilities.invokeLater

javax.swing.SwingUtilities is a collection of utility methods for Swing. The method invokeLater(Runnable doRun) causes doRun.run() to be executed asynchronously on the AWT event dispatching thread. This will happen after all pending AWT events have been processed. This method should be used when an application thread needs to update the GUI.

Run a JFrame application using SwingUtilities.invokeLater


- Create a new Java project of Java application, with main code named JavaTestSwing.java and JFrameWin.java extends javax.swing.JFrame.

- JavaTestSwing.java
package javatestswing;

import javax.swing.SwingUtilities;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaTestSwing {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(runJFrameLater);
    }
    
    static Runnable runJFrameLater = new Runnable() {

        @Override
        public void run() {
            JFrameWin jFrameWindow = new JFrameWin();
            jFrameWindow.setVisible(true);
        }
    
    };
}


- JFrameWin.java
package javatestswing;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JFrameWin extends JFrame{
    
    public JFrameWin(){
        
        this.setTitle("java-buddy.blogspot.com");
        this.setSize(500, 400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        JButton buttonExit = new JButton(" Exit ");
        buttonExit.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent ae) {
                System.exit(0);
            }
        });
        
        this.add(buttonExit);
        
    }
    
}



1 comment: