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 { static private class InnerJFrame extends JFrame{ public InnerJFrame(){ this.setTitle("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); } } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { InnerJFrame myInnerJFrame = new InnerJFrame(); myInnerJFrame.setVisible(true); } }); } }
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