To create a window in Java, you can use the JFrame
class from the javax.swing
package.
Here is an example of how to create a window with a title and a size:
import javax.swing.JFrame; public class Main { public static void main(String[] args) { JFrame frame = new JFrame("My Window"); frame.setSize(400, 300); // width, height in pixels frame.setVisible(true); } }
This creates a window with the title "My Window" and a size of 400x300 pixels. The setVisible
method is used to show the window on the screen.
You can also use the setDefaultCloseOperation
method to specify what should happen when the user closes the window. For example:
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This will exit the program when the user closes the window. Other options are JFrame.HIDE_ON_CLOSE
, which hides the window and leaves the program running, and JFrame.DISPOSE_ON_CLOSE
, which disposes of the window and releases the resources used by it.