2014-02-27 34 views
0

我有一個簡單的問題。如何在屏幕上設置JFrame的位置?當我使用setVisible()時,我希望窗口出現在屏幕上的某個位置,可能是x-y座標。可能嗎?定位JFrame

編輯:我找到了解決方案。我不得不調用setLocationByOs(false)或類似的東西,然後使用setLocation(x,y)

回答

0

嘗試搜索現有的答案,然後再問一個新的問題。在StackOverflow搜索框中輸入你的問題很容易給你一個答案。

當你初始化你的表格時,只需在調用pack()後放上setLocation(int x, int y);即可;

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

在這裏看到一個更深入的答案:Best practice for setting JFrame locations

當尋找一個方法,你可以經常發現它在JavaDoc中,例如回答你的問題:http://docs.oracle.com/javase/7/docs/api/java/awt/Window.html#setLocation%28int,%20int%29

0

嘗試這:

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

這讓JFrame出現在每個屏幕的中心。

0

有很多不同的方法可以解決這個問題。下面是如何我通常設置我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); 
    } 
} 

此類由Launcherextends Canvas implements Runnable初始化和使用線程。

frame.setLocationRelativeTo(null);是魔術詞。