0

I have a simple question. How do I set the position of a JFrame on the screen? When I use setVisible(), I want the window to appear in a certain location on the screen, perhaps by x-y coordinates. Is it possible?

EDIT: I found the solution. I had to call setLocationByOs(false) or something like that, then use setLocation(x,y)

3 Answers3

1

Try this:

        final Dimension d = this.getToolkit().getScreenSize(); 
        this.setLocation((int) ((d.getWidth() - this.getWidth()) / 2), (int) ((d.getHeight() - this.getHeight()) / 2));

This lets the JFrame appear in the center of every screen.

0

Try searching for an existing answer before asking a new question. Entering your question into the StackOverflow search box would easily have given you an answer.

When you initialize your form just put setLocation(int x, int y); on the line after you call pack();

pack();
setLocation(int x, int y);

See here for a more in depth answer: Best practice for setting JFrame locations

When looking for a method, you can often find it in the JavaDocs, for example the answer to your question: http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#setLocation%28int,%20int%29

Community
  • 1
  • 1
sorifiend
  • 5,927
  • 1
  • 28
  • 45
0

There are many different ways you could approach this. Below is how I usually setup my JFrames:

import java.awt.Canvas;
import javax.swing.JFrame;

public class Window extends Canvas{
    public Window(Launcher launcher){
        JFrame frame = new JFrame("Example");
        frame.setSize(800,480);
        frame.setResizable(false);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(launcher);
        frame.setVisible(true);
        launcher.setFrame(frame);
    }
}

This class is initialized by Launcher which extends Canvas implements Runnable and uses threading.

frame.setLocationRelativeTo(null); is the magic word.

Reason
  • 105
  • 11