Let's start with the simplest Swing program.
We will use a JFrame, which is a top-level container, to create our first application. To create and display a JFrame, we need to do the following:
To create a JFrame object, we can use the constructors of the JFrame class.
In the following code we use the constructor which takes a string. The string value will be displayed as the title for the JFrame.
Classes representing Swing components are in the javax.swing package, so is the JFrame class.
The following code creates a JFrame object with its title set to "Swing":
// Create a JFrame object JFrame frame = new JFrame("Swing");
When we create a JFrame object, by default, it is not visible.
We have to call its setVisible(boolean visible)
method to make it visible.
true parameter makes the frame visible, to hide the frame pass false
to the setVisible method.
To Make the JFrame visible on the screen
frame.setVisible(true);
The following code wraps the two statements, to create and display a JFrame, into one statement.
new JFrame("Swing").setVisible(true);
import javax.swing.JFrame; /*from w ww . jav a2 s . c o m*/ public class Main { public static void main(String[] args) { // Create a frame JFrame frame = new JFrame("Swing"); // Display the frame frame.setVisible(true); } }
We can define one of the four behaviors of a JFrame to determine what happens when the JFrame is closed.
The constants are defined in the javax.swing.WindowsConstants interface.
The JFrame class implements the WindowsConstants interface. We can reference all these constants using JFrame.CONSTANT_NAME syntax or we can use the WindowsConstants.CONSTANT_NAME syntax.
The four constants are
DO_NOTHING_ON_CLOSE
HIDE_ON_CLOSE
DISPOSE_ON_CLOSE
EXIT_ON_CLOSE
We can set the default close behavior of a JFrame by passing one of the four constants to its setDefaultCloseOperation() method.
The following code shows how to exit the application when the JFrame is closed
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
The above JFrame has no viewable area. It displays only the title bar.
We need to set the size and position of your JFrame to show its content area.
The size of a frame is defined by its width and height in pixels and we can set them using setSize(int width, int height) method.
The position is defined by the (x, y) coordinates in pixels of the top-left corner of the JFrame with respect to the top-left corner of the screen.
By default, its position is set to (0, 0) and this is the reason the JFrame was displayed at the top-left corner of the screen.
We can set the (x, y) coordinates of the JFrame using its setLocation(int x, int y)
method.
To set its size and position in one step, use its setBounds(int x, int y, int width, int height) method.
The following code gives size and sets position of the JFrame.
import javax.swing.JFrame; /* ww w . ja v a2s . c o m*/ public class Main { public static void main(String[] args) { JFrame frame = new JFrame("Swing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set the x, y, width and height properties frame.setBounds(50, 50, 200, 200); frame.setVisible(true); } }
To position a JFrame in the center of the screen, call its setLocationRelativeTo() method with a null argument.
When adding UI controls to JFrame, we add them to the content pane of JFrame.
The content pane from JFrame holds the Swing components of a JFrame.
To get the reference of the content pane from JFrame use the following code.
// Create a JFrame JFrame frame = new JFrame("Test"); // Get the reference of the content pane Container contentPane = frame.getContentPane();
After getting the reference for the content pane from JFrame we can add components by using the add() method.
// Add aComponent to contentPane contentPane.add(aComponent);
The following code adds a JButton to JFrame. An object of the JButton class represents a button, such as an OK button on a message box.
A JButton contains label text. The next line uses the Close as JButton's label text.
// Create a JButton with Close text JButton closeButton = new JButton("Close");
To add closeButton to the content pane of a JFrame, we have to do two things:
Get the reference of the content pane of the JFrame.
Container contentPane = frame.getContentPane();
Call the add() method of the content pane.
contentPane.add(closeButton);
To add a JButton to JFrame using one line of code, combine all statements into one.
frame.getContentPane().add(new JButton("Close"));
The full source code.
import java.awt.Container; //from ww w. j a va2 s .c o m import javax.swing.JButton; import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame frame = new JFrame("JFrame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Container contentPane = frame.getContentPane(); // Add a close button JButton closeButton = new JButton("Close"); contentPane.add(closeButton); // set the size of the frame 300 x 200 frame.setBounds(50, 50, 300, 200); frame.setVisible(true); } }
The pack() method of the JFrame examines all the components on the JFrame and decides their preferred size and sets the size of the JFrame just enough to display all the components.
When we call pack() method, we do not need to set the size of the JFrame. The pack() method will calculate the size of the JFrame and set it.
When using the pack() method, we don't need to call the setBounds() method.
To position a JFrame after pack() method, use setLocation(x, y) method.
import java.awt.Container; // w ww . j a v a 2 s .co m import javax.swing.JButton; import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame frame = new JFrame("JFrame"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Add a close button JButton closeButton = new JButton("Close"); Container contentPane = frame.getContentPane(); contentPane.add(closeButton); // Calculates and sets appropriate size for the frame frame.pack(); frame.setVisible(true); } }
We can set the state of a JFrame programmatically using the setExtendedState(int state) method.
The state is specified using constants defined in the java.awt.Frame class from which the JFrame class is inherited.
To display the JFrame maximized
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
The following table lists Constants That Define States of a JFrame
JFrame State Constants | Description |
---|---|
NORMAL | JFrame is displayed in normal size. |
ICONIFIED | JFrame is displayed in minimized state. |
MAXIMIZED_HORIZ | JFrame is displayed maximized horizontally, but in normal size vertically. |
MAXIMIZED_VERT | JFrame is displayed maximized vertically, but in normal size horizontally. |
MAXIMIZED_BOTH | JFrame is displayed maximized horizontally as well as vertically. |
Sometimes we may want to use a default button in your JFrame or JDialog. A default button is an instance of the JButton class, which is activated when the user presses a key on the keyboard.
A key that activates the default button is defined by the look-and-feel.
Typically, the key to activate the default button is the Enter key.
We can set a default button for a JRootPane, which is present in a JFrame, JDialog, JWindow, JApplet, and JInternalFrame.
Usually, we set the OK button as a default button on a JDialog. If a JRootPane has a default button set, pressing the Enter key will activate that button.
// Create a JButton JButton okButton = new JButton("OK"); // Set okButton as the default button frame.getRootPane().setDefaultButton(okButton);
We can add a window listener to a JFrame or any other top-level Swing window that will notify changes in a window's state.
The following code adds a window listener to a JFrame named frame.
If we are interested in listening for only few window state changes, we can use the WindowAdapter class instead of the WindowListener interface.
The WindowAdapter class provides an empty implementation of all the seven methods in the WindowListener interface.
import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.IOException; //ww w . j a v a 2s. c o m import javax.swing.JFrame; public class Main { public static void main(String[] args) throws IOException { JFrame frame = new JFrame(); frame.addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) { System.out.println("JFrame has been made visible first time"); } @Override public void windowClosing(WindowEvent e) { System.out.println("JFrame is closing."); } @Override public void windowClosed(WindowEvent e) { System.out.println("JFrame is closed."); } @Override public void windowIconified(WindowEvent e) { System.out.println("JFrame is minimized."); } @Override public void windowDeiconified(WindowEvent e) { System.out.println("JFrame is restored."); } @Override public void windowActivated(WindowEvent e) { System.out.println("JFrame is activated."); } @Override public void windowDeactivated(WindowEvent e) { System.out.println("JFrame is deactivated."); } }); // Use the WindowAdapter class to intercept only the window closing event frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.out.println("JFrame is closing."); } }); } }
We are done with a window (JFrame, JDialog or JWindow), we should call its dispose() method.
dispose() method makes a window invisible and release the resources to the operating system.