Sunday, February 10, 2013

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

Last article demonstrate how to "Create GUI application, by instantiating outer class of JFrame". Alternatively, we can code the extended JFrame as inner class, named InnerJFrame.

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
public class JavaJFrameApplication {
    static private class InnerJFrame extends JFrame{
        public InnerJFrame(){
            this.setTitle("static inner JFrame");
            this.setSize(300, 200);
            JButton buttonExit = new JButton("Exit");
            buttonExit.addActionListener(new ActionListener(){
                public void actionPerformed(ActionEvent e) {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){

            public void run() {
                InnerJFrame myInnerJFrame = new InnerJFrame();

Please notice that InnerJFrame have to be declared static in this implementation, otherwise error of "non-static variable this cannot be referenced from a static context" will be complained. It's because instance of non-static inner class(InnerJFrame) can exist only within an instance of outer class(JavaJFrameApplication). At the time of main() run, object of JavaJFrameApplication have not been instantiated.

If you prefer declare the inner class as non-static, read the article "Create GUI application, by instantiating non-static inner class of JFrame".

No comments:

Post a Comment