Create a JFrame GUI with SWING
The window is the main panel that encompasses all the widgets, and is implemented as an instance of the javax.swing.jframe which is an upgraded version of the java.awt.Frame. This new class supports the Swing architecture and implements the event model of AWT.JFrame has a content pane which is the main panel, it includes the other components: JPanel, JMenu, JButton, etc.
Creating and displaying windows
import javax.swing.JFrame;Output
public class Test extends JFrame{
public static void main(String[] args) {
//1. Create a JFrame
JFrame window = new JFrame("JFrame Test");
//2. Stop the application after closing the window
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//3. Set the dimension width and height
window.setSize(400,300);
//4. Optional: centered position
window.setLocationRelativeTo(null);
//5. display window
window.setVisible(true);
}
}
Code Explained:
1. The first statement creates a window with the input title using an instance of the JFrame.
2 class. EXIT_ON_CLOSE exits the program after the .
3 window closes. The method setSize gives the width and height. If we want java to automatically detect the dimension, we use the pack method according to the dimensions of the components inside.
4. setLocationRelativeTo(null) positions the window in the center of the screen. We also have setLocation(x,y).
5. setVisible make the window visible in the screen.
How to insert widgets
The add() allows you to add components. In this example we will insert a JTextArea and a JButton:
import javax.swing.JFrame;Output
import javax.swing.JTextArea;
public class Test extends JFrame{
public static void main(String[] args) {
JFrame frame = new JFrame("JFrame test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
JTextArea jta = new JTextArea("Type a text");
//resize the textArea
jta.setPreferredSize(new Dimension(400,300));
//put a text box in the center
frame.add(jta);
//put a button in the south
frame.add(new JButton("erase"),BorderLayout.SOUTH);
//automatically calculates the window size after by summing the //dimension of JtextArea and JButton
frame.pack();
}
}
The text box is located in the center, by default it is inserted in the center so it is not necessary to define the region: frame.add(jta, BorderLayout.CENTER). In this example, we can add without retrieving the content pane with the method getContentPane.