Sunday, February 10, 2013

Create GUI application, by instantiating non-static inner class of JFrame.

Last article demonstrate "Create GUI application, by instantiating static inner class of JFrame". If the inner class is declared as non-static, it cannot be accessed directly in main(). You can instantiate the outer class in main(), and then instantiate the inner class in constructor.

package javajframeapplication;

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

/**
 *
 * @web http://java-buddy.blogspot.com/
 */
public class JavaJFrameApplication {
    
    private class InnerJFrame extends JFrame{
    
        public InnerJFrame(){
            this.setTitle("non-static inner JFrame");
            this.setSize(300, 200);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            
            JButton buttonExit = new JButton("Exit");
            buttonExit.addActionListener(new ActionListener(){
                @Override
                public void actionPerformed(ActionEvent e) {
                    System.exit(0);
                }
            });
            
            this.add(buttonExit);
        }
    
    }
    
    JavaJFrameApplication(){
        InnerJFrame myInnerJFrame = new InnerJFrame();
        myInnerJFrame.setVisible(true);
    }
    
    public static void main(String[] args) {
        
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run() {
                
                JavaJFrameApplication myJavaJFrameApplication =
                        new JavaJFrameApplication();
            }
        });
    }
}


GUI application, by instantiating non-static inner class of JFrame.
GUI application, by instantiating non-static inner class of JFrame.


No comments:

Post a Comment