Sunday, February 10, 2013

Create GUI application, by instantiating outer class of JFrame.

This example demonstrate how to create GUI for Java Application, by instantiating outer class of JFrame.

GUI for Java Application

Create a class OuterJFrame.java, extends JFrame.
package javajframeapplication;

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

public class OuterJFrame extends JFrame{

public OuterJFrame(){
this.setTitle("Java-Buddy");
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);
}
}


Modify main class, instantiate OuterJFrame class in main() method.
package javajframeapplication;

import javax.swing.SwingUtilities;

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

public static void main(String[] args) {

SwingUtilities.invokeLater(new Runnable(){

@Override
public void run() {

OuterJFrame myOuterJFrame = new OuterJFrame();
myOuterJFrame.setVisible(true);
}
});
}
}


We can also implement our custom JFrame as inner class. Refer:


No comments:

Post a Comment