How to use Java Swing components in a window?

The steps to create a window using Swing components are as follows:

  1. Import the necessary Swing classes.
import javax.swing.JFrame;
import javax.swing.JPanel;
  1. A window in Java that displays a graphical user interface.
JFrame frame = new JFrame("Swing Window");
  1. Adjust the size and position of the window.
frame.setSize(400, 300);
frame.setLocationRelativeTo(null); // 居中显示窗口
  1. Setting the close operation of the window.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  1. A panel in Java Swing framework.
JPanel panel = new JPanel();
  1. Add other Swing components (such as buttons, text fields, etc.) to the panel.
panel.add(new JButton("Button"));
panel.add(new JTextField("Text Field"));
  1. Set the panel as the content pane of the window.
frame.setContentPane(panel);
  1. 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.

bannerAds