How to use Java Swing components in a window?
The steps to create a window using Swing components are as follows:
- Import the necessary Swing classes.
import javax.swing.JFrame;
import javax.swing.JPanel;
- A window in Java that displays a graphical user interface.
JFrame frame = new JFrame("Swing Window");
- Adjust the size and position of the window.
frame.setSize(400, 300);
frame.setLocationRelativeTo(null); // 居中显示窗口
- Setting the close operation of the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- A panel in Java Swing framework.
JPanel panel = new JPanel();
- Add other Swing components (such as buttons, text fields, etc.) to the panel.
panel.add(new JButton("Button"));
panel.add(new JTextField("Text Field"));
- Set the panel as the content pane of the window.
frame.setContentPane(panel);
- Display window
frame.setVisible(true);
Here is the complete example code:
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class SwingWindowExample {
public static void main(String[] args) {
JFrame frame = new JFrame("Swing Window");
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
panel.add(new JButton("Button"));
panel.add(new JTextField("Text Field"));
frame.setContentPane(panel);
frame.setVisible(true);
}
}
Running the above code will display a window with both a button and a text box.