java create jframe

‮www‬.lautturi.com
java create jframe

To create a JFrame in Java, you can use the JFrame class from the javax.swing package.

Here is an example of how to create a basic JFrame with a title and size:

import javax.swing.JFrame;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("My Frame");
        frame.setSize(400, 300);
        frame.setVisible(true);
    }
}

This creates a new JFrame object with the specified title and size, and makes it visible on the screen using the setVisible method.

You can also use the setDefaultCloseOperation method to specify what should happen when the user closes the window. For example, to exit the application when the user closes the window, you can use the following code:

import javax.swing.JFrame;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("My Frame");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
}

To add components to the frame, such as buttons, labels, and text fields, you can use the add method of the JFrame class. For example, to add a button to the frame, you can use the following code:

import javax.swing.JFrame;
import javax.swing.JButton;

public class Main {
    public static void main(String[] args) {
        JFrame frame = new JFrame("My Frame");
        frame.setSize(400, 300);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JButton button = new JButton("Click me");
        frame.add(button);

        frame.setVisible(true);
    }
}

This creates a new JButton object with the text "Click me" and adds it to the frame using the add method.

Created Time:2017-11-03 00:14:52  Author:lautturi