How to set the content in a Java JFrame?

To set the contents of a JFrame, you can use methods from the JFrame class to add and manage various components.

First, create a JFrame object.

JFrame frame = new JFrame("My Frame");

Next, adjust the size and position of the window:

frame.setSize(500, 500); // 设置窗口大小为500x500像素
frame.setLocationRelativeTo(null); // 将窗口位置设置为屏幕中央

Next, create the components that need to be added to the window, such as buttons or labels.

JButton button = new JButton("Click me!");
JLabel label = new JLabel("Hello, World!");

You can use layout managers to control the positions and sizes of components. For example, you can use the FlowLayout layout manager to arrange components in a left-to-right order.

frame.setLayout(new FlowLayout());

Next, add the components to the window.

frame.add(button);
frame.add(label);

Finally, make the window visible and close it.

frame.setVisible(true); // 将窗口设置为可见
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置关闭窗口时的操作为退出程序

This way, you can set the content of the JFrame. You can also use other layout managers and components as needed to create more complex user interfaces.

bannerAds