how to create new frame with java swing

how to create new frame with java swing

To create a new JFrame (a top-level window) in Java Swing, you can use the following steps:

  1. Import the necessary classes:
ref‮l:ot re‬autturi.com
import javax.swing.JFrame;
  1. Create a new JFrame object:
JFrame frame = new JFrame();
  1. Set the size and location of the 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.

  1. Set the title of the JFrame:
frame.setTitle(title);

Here, title is the text that will be displayed in the title bar of the JFrame.

  1. Add components to the 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);
  1. Set the default close operation of the 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.

  1. Make the 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!".

Created Time:2017-11-01 20:42:48  Author:lautturi