I want to resize and position a JFrame in Java. How can I achieve that?

Java 8Object Oriented ProgrammingProgramming

To resize and position JFrame, use the Dimensions class. Here, we have set the bounds for the frame −

int width = 500;
int height = 400;
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
frame.setBounds((int) size.getWidth() - width, 0, width, height);

The following is an example to resize and poisiton a frame −

Example

package my;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Toolkit;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
public class SwingDemo {
   public static void main(String[] args) throws Exception {
      JFrame.setDefaultLookAndFeelDecorated(true);
      JFrame frame = new JFrame("Register!");
      JLabel label1, label2, label3;
      frame.setLayout(new GridLayout(2, 2));
      label1 = new JLabel("Id", SwingConstants.CENTER);
      label2 = new JLabel("Age", SwingConstants.CENTER);
      label3 = new JLabel("Password", SwingConstants.CENTER);
      JTextField emailId = new JTextField(20);
      JTextField age = new JTextField(20);
      JPasswordField passwd = new JPasswordField();
      passwd.setEchoChar('*');
      frame.add(label1);
      frame.add(label2);
      frame.add(label3);
      frame.add(emailId);
      frame.add(age);
      frame.add(passwd);
      int width = 500;
      int height = 400;
      Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
      frame.setBounds((int) size.getWidth() - width, 0, width, height);
      frame.setVisible(true);
   }
}

Output


raja
Updated on 30-Jul-2019 22:30:26

Advertisements