To create a new JFrame (a top-level window) in Java Swing, you can use the following steps:
import javax.swing.JFrame;
JFrame object:JFrame frame = new JFrame();
JFrame:frame.setSize(width, height); frame.setLocation(x, y);
Here, width and height are the dimensions of the JFrame in pixels, and x and y are the coordinates of the top-left corner of the JFrame on the screen.
JFrame:frame.setTitle(title);
Here, title is the text that will be displayed in the title bar of the JFrame.
JFrame:You can use the add method to add components to the JFrame, such as buttons, labels, and text fields. For example:
frame.add(button); frame.add(label); frame.add(textField);
JFrame:frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This specifies what should happen when the user closes the JFrame. In this case, the EXIT_ON_CLOSE constant specifies that the application should exit when the JFrame is closed.
JFrame visible:frame.setVisible(true);
This will display the JFrame on the screen.
Here's an example of a complete program that creates a JFrame with a button and a label:
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
public class Example {
public static void main(String[] args) {
// Create a new JFrame
JFrame frame = new JFrame();
// Set the size and location of the JFrame
frame.setSize(400, 300);
frame.setLocation(200, 100);
// Set the title of the JFrame
frame.setTitle("Example JFrame");
// Create a button and a label
JButton button = new JButton("Click me!");
JLabel label = new JLabel("Hello, world!");
// Add the button and label to the JFrame
frame.add(button);
frame.add(label);
// Set the default close operation of the JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make the JFrame visible
frame.setVisible(true);
}
}
This will create a JFrame with a button and a label, and when the button is clicked, the label will change to say "Hello, world!".