How can i get my JFrame to open centre screen? [duplicate] - java

While working with Java, I find it hard to position my main window in the center of the screen when I start the application.
Is there any way I can do that?
It doesn't have to be vertically centered, horizontal alignment is the more important goal for me. But vertical alignment is also welcome.

Use setLocationRelativeTo(null)
This method has a special effect when you pass it a null. According to the Javadoc:
If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.
This should be done after setting the size or calling pack(), but before setting it visible, like this:
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);

I always did it in this way:
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
where this is the JFrame involved.

You can call JFrame.setLocationRelativeTo(null) to center the window. Make sure to put this before JFrame.setVisible(true)

Just click on form and go to JFrame properties, then Code tab and check Generate Center.

As simple as this...
setSize(220, 400);
setLocationRelativeTo(null);
or if you are using a frame then set the frame to
frame.setSize(220, 400);
frame.setLocationRelativeTo(null);
For clarification, from the docs:
If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.

i am using NetBeans IDE 7.2.1 as my developer environmental and there you have an option to configure the JForm properties.
in the JForm Properties go to the 'Code' tab and configure the 'Generate Center'.
you will need first to set the Form Size Policy to 'Generate Resize Code'.

I am using NetBeans IDE 7.3 and this is how I go about centralizing my JFrame
Make sure you click on the JFrame Panel and go to your JFrame property bar,click on the Code bar and select Generate Center check box.

If you use NetBeans, simply click on the frame on the design view, then the code tab on its properties. Next, check 'Generate Center'. That will get the job done.

If you explicitly setPreferredSize(new Dimension(X, Y)); then it is better to use:
setLocation(dim.width/2-this.getPreferredSize().width/2, dim.height/2-this.getPreferredSize().height/2);

You can use this method, which allows the JFrame to be centered and full screen at the same time.
yourframe.setExtendedState(JFrame.MAXIMIZED_BOTH);

In Net Beans GUI -
go to jframe (right click on jFrame in Navigator) properties, under code, form size policy property select Generate Resize Code. In the same window, Untick Generate Position and tick Generate Size and Center.
Enjoy programming.
Ramana

I will provide 3 methods to your question :
You can either use the simplest method to center it, relative to your viewport, which is :
setLocationRelativeTo(null);
The second one, is to use :
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2 - frame.getSize().width/2, dim.height/2 - frame.getSize().height/2);
And the third one, the most customizable one, is a bit more complicated, but is the most useful. (in my opinion) :
1.) You create a JButton and add it to your panel.
2.) You add an ActionListener event to it.
3.) On your button click, you invoke the method :
frame.getLocationOnScreen(); which you need to save to a Point
variable => Point location = frame.getLocationOnScreen;
4.) After that, you invoke : System.out.println(location);, so that you can get the location on the screen that you want to put your frame
to - it will print it to the console.
5.) You delete the button and ActionListener, after you've got the x, y coordinates.
6.) You invoke : frame.setLocation(x, y);
That's it.
The code looks like this :
JButton button = new JButton();
button.setText("Get Location");
panel.add(button);
ActionListener onButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Point location = frame.getLocationOnScreen();
System.out.println(location);
}
};
button.addActionListener(onButton);
After you have the location, do this :
frame.setLocation(445, 195);
Hope I was helpful. ^

Related

Resize a JFrame, which has no border, using a mouse

I am working on a Java desktop application using javax.swing.
I want make my application border-less and at the same time resizeable.
When I remove the border using the frame.setUndecorated(true); method I can no longer resize the frame using mouse clicks and drags.
How can I hide the border of the frame and still let the user resize it?
Frames allow a user to interact with the JFrame using their mouse. If you remove the frame then you cannot use it to move or resize the frame. You can reimplement this functionality yourself (not sure why you'd want to but of course experimenting is always fun!).
First you must somehow get user mouse events. By creating a custom JComponent, maybe called ResizeGrip, and placing it in the bottom right of your frame you can visually show your user that they can still resize the frame. You can then implement a MouseListener to see when the user has clicked and dragged your ResizeGrip.
Then you need to turn those event detections into instructions to resize the frame pragmatically, that is via someJFrame.setSize(newWidth, newHeight);. You will also need to do something similar if you want to move the frame.
Check out Resizing Component for a general purpose class that will allow you to resize any component.
The class is a MouseListener that installs itself on the components you specify.
The basic code to add it to your frame would be:
JFrame frame = new JFrame("SSCCE");
frame.setUndecorated(true);
ComponentResizer cr = new ComponentResizer();
cr.registerComponent(frame);
You can control which sides can be dragged by specifying the "drag insets". The default value is 5 for all sides which means you can resize any size. You could limit the frame to be resized only horizontally by using:
cr.setDragInsets( new Insets(0, 0, 0, 5) );

How do I create a new JFrame, whos' location is set to the middle of another JFrame?

I'm new to Java and this is what I'm trying to do:
I have frame1, which has a JButton that, once clicked, creates a new JFrame on top of frame1, which I call frame2. I basically want frame2 to be created in the middle of frame1. How do I do this?
You set the location of frame2 relative to the location of frame1.
//Initialize your frames
frame2.setLocationRelativeTo(frame1);
This should place frame2 right on top of frame1.
The easiest way to do it is Marv's, but if you want to do it with Maths, try this instead.
Point offSet=frame1.getLocation();
Dimension loc1=frame1.getSize();
Dimension loc2=frame2.getSize();
double newX=offSet.getX()+loc1.getWidth()/2.0-loc2.getWidth()/2.0;
double newY=offSet.getY()+loc1.getHeight()/2.0-loc2.getHeight()/2.0;
frame2.setLocation((int)Math.floor(newX), (int)Math.floor(newY));
frame2.setVisible(true);
This will center frame2 on top of frame1.
If you choose the .setLocationRelativeTo() method, don't forget to re-use frame2.setVisible(true) if you did frame2.setVisible(true) before frame1.setVisible(true)
Use setLocationRelativeTo(Component c) (use this doc if you're using Java 8) as follows:
// center in parent
frame2.setLocationRelativeTo(frame1);
You can also center the component in the screen using
// center in screen
frame2.setLocationRelativeTo( null );
Check out this question if you're still having issues.

Set JFrame to center of Screen in NetBeans

I am developing a java swing desktop application
with NetBeans and I want to set the JFrame to the centre of the screen.
from the net I understand that I can use
setLocationRelativeTo(null);
to set the frame to the centre
But i am unable to insert the code into the NetBeans IDE
because both the frame.pack()
and frame.setVisible() are generated codes of the NetBeans 7 IDE
and it will not permit any code insertion between the two methods.
I need to to obtain the following :
frame.pack()
setLocationRelativeTo(null);
frame.setVisible()
Any suggestion on how to fix the problem?
Properties ->Code -> check out Generate Center
On the constructor of the frame, you have this:
public frame() {
initComponents();
}
You only have to put this line: "this.setLocationRelativeTo(null);"
under the "initComponents();"
And you'll have this:
public frame() {
initComponents();
this.setLocationRelativeTo(null);
}
Run it, and it the frame should show on the center of the screen =)
Follow the following simple steps:
select the frame and go to the properties.
click on code section and click on checkbox Generate Center.
That's it.
Is setVisible() on generated code? Strange. Anyway, you can right click the JFrame in Navigator and select Properties. Go to Code and select it to do nothing. Then manually insert you code after initComponents() in the JFrame constructor.
I am not sure if you got an answer to your problem, but a solution was given in the following link by Wade Chandler on the NetBeans forum. Unfortunately the originator of the query being answered was impatient to say the least and you have to work through some angst to get to the answer.
http://forums.netbeans.org/ptopic37419.html
Wade shows how to centre the GUI and what aspects of the code you can modify.
As an aside, if you want to place the GUI at a set position on the screen then you can use:
This requires access to the Properties ->Code window as well.
1. Ensure you select the Frame (not a component or outside!)
2. Go to the Code tab in the properties window for the JFrame.
3. Locate the "Form Size Policy" label.
4. In the drop-down select "Generate Resize Code".
5. Modify the form position by clicking the "..." next to it.
6. Also, make sure "Generate Size" is checked as well.
If you want to place the GUI top left on the screen then use the default [0,0] for form position. To position a second GUI next to the first use [450,0]. In this case the x-value has been changed to 450, the Y-value is kept a 0. To move the GUI down the screen then change the Y-value from 0 to say 450.
Finally, there is a NetBeans bug 226740 that can result in problems when trying to centre some aspects of a GUI. It will probably not affect you, but it is useful to be aware of it.
Regards
Derek
From the link #DerekMannering posted:
Netbeans actually generates centering logic on its own versus through
property use, so you won't see setLocationRelativeTo option. Go to the
Code tab in the properties window. Locate the "Form Size Policy" label
in the Code tab. In the drop-down select "Generate Resize Code". Then
make sure the property with the label "Generate Center" is checked.
Too you'll want to make sure "Generate Size" is checked as well.
Should be by default, but you should check anyways. Now, that will
work best for JFrame or Frame extensions.
Within the Netbeans Designer area, choose your JFrame, go to code.
Within code, change Form Size Policy to "Generate Resize Code"
Then choose the Generate Center Option.
at the constructor writing give code below will make your jframe at the center of the screen
public ProjectWork_jframe() {
initComponents();
Dimension screenSize,frameSize;
int x,y;
screenSize=Toolkit.getDefaultToolkit().getScreenSize();
frameSize=getSize();
x=(screenSize.width-frameSize.width)/2;
y=(screenSize.height-frameSize.height)/2;
setLocation(x, y);
}
try....
public class_name{
initComponents();
setLocationRelativeTo(this);
}

How to hide the default minimize/maximize and close buttons on JFrame window in Java?

I would like to know if it is possible to create a JFrame window which has no default maximize/minimize(-) and close(x) buttons! I have added custom buttons on each frame so that the user does not have to mess around with the default ones on the top right corner of the window!
You can use JWindow because is by default un_decorated, but you can setUndecorated() for JFrame/JDialog
another ways are
implements WindowListener
setDefaultCloseOperations
Use JFrame.setDefaultLookAndFeelDecorated. It may not be the exact thing you need but doc says,
Provides a hint as to whether or not newly created JFrames should have
their Window decorations (such as borders, widgets to close the
window, title...) provided by the current look and feel.
Try this code:
JFrame frame = new JFrame("Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(100, 100);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);
frame.setVisible(true);
This will remove the entire titlebar. Also take a look at this thread.
Otherwise use JWindows.
JFrame.setDefaultCloseOperation(frame.DO_NOTHING_ON_CLOSE);
Will make the 'X' button no functioning. It's works for me.
If you are using Netbean then just unselect the resizable option in properties.
It will only disable Minimize/Maximize Button.
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.NONE);

How to set JFrame to appear centered, regardless of monitor resolution?

While working with Java, I find it hard to position my main window in the center of the screen when I start the application.
Is there any way I can do that?
It doesn't have to be vertically centered, horizontal alignment is the more important goal for me. But vertical alignment is also welcome.
Use setLocationRelativeTo(null)
This method has a special effect when you pass it a null. According to the Javadoc:
If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.
This should be done after setting the size or calling pack(), but before setting it visible, like this:
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
I always did it in this way:
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
this.setLocation(dim.width/2-this.getSize().width/2, dim.height/2-this.getSize().height/2);
where this is the JFrame involved.
You can call JFrame.setLocationRelativeTo(null) to center the window. Make sure to put this before JFrame.setVisible(true)
Just click on form and go to JFrame properties, then Code tab and check Generate Center.
As simple as this...
setSize(220, 400);
setLocationRelativeTo(null);
or if you are using a frame then set the frame to
frame.setSize(220, 400);
frame.setLocationRelativeTo(null);
For clarification, from the docs:
If the component is null, or the GraphicsConfiguration associated with this component is null, the window is placed in the center of the screen.
i am using NetBeans IDE 7.2.1 as my developer environmental and there you have an option to configure the JForm properties.
in the JForm Properties go to the 'Code' tab and configure the 'Generate Center'.
you will need first to set the Form Size Policy to 'Generate Resize Code'.
I am using NetBeans IDE 7.3 and this is how I go about centralizing my JFrame
Make sure you click on the JFrame Panel and go to your JFrame property bar,click on the Code bar and select Generate Center check box.
If you use NetBeans, simply click on the frame on the design view, then the code tab on its properties. Next, check 'Generate Center'. That will get the job done.
If you explicitly setPreferredSize(new Dimension(X, Y)); then it is better to use:
setLocation(dim.width/2-this.getPreferredSize().width/2, dim.height/2-this.getPreferredSize().height/2);
You can use this method, which allows the JFrame to be centered and full screen at the same time.
yourframe.setExtendedState(JFrame.MAXIMIZED_BOTH);
In Net Beans GUI -
go to jframe (right click on jFrame in Navigator) properties, under code, form size policy property select Generate Resize Code. In the same window, Untick Generate Position and tick Generate Size and Center.
Enjoy programming.
Ramana
I will provide 3 methods to your question :
You can either use the simplest method to center it, relative to your viewport, which is :
setLocationRelativeTo(null);
The second one, is to use :
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(dim.width/2 - frame.getSize().width/2, dim.height/2 - frame.getSize().height/2);
And the third one, the most customizable one, is a bit more complicated, but is the most useful. (in my opinion) :
1.) You create a JButton and add it to your panel.
2.) You add an ActionListener event to it.
3.) On your button click, you invoke the method :
frame.getLocationOnScreen(); which you need to save to a Point
variable => Point location = frame.getLocationOnScreen;
4.) After that, you invoke : System.out.println(location);, so that you can get the location on the screen that you want to put your frame
to - it will print it to the console.
5.) You delete the button and ActionListener, after you've got the x, y coordinates.
6.) You invoke : frame.setLocation(x, y);
That's it.
The code looks like this :
JButton button = new JButton();
button.setText("Get Location");
panel.add(button);
ActionListener onButton = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Point location = frame.getLocationOnScreen();
System.out.println(location);
}
};
button.addActionListener(onButton);
After you have the location, do this :
frame.setLocation(445, 195);
Hope I was helpful. ^

Categories