How to position a JFrame
when you create a frame,by default the frame is positioned at the top-left corner of your screen,until you specify the desired location.
To get the attention of the user this default orientation of the frame is not enough.So we need to relocate the frame according to the user needs.There are three methods to relocate a frame.
Method 1:
You can use the setLocation(int x,int y) method of the Component class to locate the frame to your desired location.
In this method,first argument specifies the distance from the left side of the screen(pixels) and the second argument specifies distance from the top of the screen(pixels).
Program:
Myframe.java
import javax.swing.*;
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}
import java.util.*;
class Myframe
{
public static void main(String args[])
{
Firstframe f1=new Firstframe();
f1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f1.setVisible(true);
}
}
Firstframe.java
import javax.swing.*;
import java.util.*;
import java.awt.*;
class Firstframe extends JFrame
{
Firstframe()
{
setSize(200,200);
setLocation(50,50);// Here i have specified the location as (50,50)
import java.util.*;
import java.awt.*;
class Firstframe extends JFrame
{
Firstframe()
{
setSize(200,200);
setLocation(50,50);// Here i have specified the location as (50,50)
setTitle("My FirstFrame");
}
}
}
}
Specifying the location of the frame is same as specifying a point in a graph,where in the (x,y) co-ordinates specify the starting point from where the frame should be drawn.
Method 2:
There is a method(function) named setLocationByPlatform(boolean b) available in the Windows class which decides the suitable location for the frame (randomly)rather than letting you to choose the desired location.
If you call this method with a boolean value of true then the platform will pick a suitable location.
In the above program instead of using the setLocation() method use this setLocationByPaltform(true) method.
Method 3:
Using the setBounds(int x,int y,int width,int height) you can choose the desired location and the desired size of the frame.
Description:
int x- distance from the left side of the screen
int y-distance from the top of the screen
int Width - specifies the width of the frame
int Height- specifies the height of the frame.
In the program that i have mentioned before instead of using the setLocation() method use the setBounds() method.
0 comments:
Post a Comment