2012-03-17 93 views
6

我需要在屏幕上放置JFrame。但是我不能讓它們出現在屏幕底部的右側。屏幕右下角的位置

請有人能解釋我如何定位他們,如果你能描述如何去做,那會很棒。

這是目前爲止的代碼。

//Gets the screen size and positions the frame left bottom of the screen 
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
    GraphicsDevice defaultScreen = ge.getDefaultScreenDevice(); 
    Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds(); 
    int x = (int)rect.getMinX(); 
    int y = (int)rect.getMaxY()- frame.getHeight(); 
    frame.setLocation(x ,y - 45); 
+0

有些平臺限制了這一點,如[這裏](http://stackoverflow.com/a/2188981/230513)所述。 – trashgod 2012-03-17 22:04:54

回答

13

試試下面的例子。請注意0​​「如何確定Window的尺寸以適合其子組件的首選尺寸和佈局。」

import java.awt.Dimension; 
import java.awt.EventQueue; 
import java.awt.GraphicsDevice; 
import java.awt.GraphicsEnvironment; 
import java.awt.Rectangle; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

/** @see http://stackoverflow.com/q/9753722/230513 */ 
public class LowerRightFrame { 

    private void display() { 
     JFrame f = new JFrame("LowerRightFrame"); 
     f.add(new JPanel() { 

      @Override // placeholder for actual content 
      public Dimension getPreferredSize() { 
       return new Dimension(320, 240); 
      } 

     }); 
     f.pack(); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); 
     GraphicsDevice defaultScreen = ge.getDefaultScreenDevice(); 
     Rectangle rect = defaultScreen.getDefaultConfiguration().getBounds(); 
     int x = (int) rect.getMaxX() - f.getWidth(); 
     int y = (int) rect.getMaxY() - f.getHeight(); 
     f.setLocation(x, y); 
     f.setVisible(true); 
    } 

    public static void main(String[] args) { 
     EventQueue.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new LowerRightFrame().display(); 
      } 
     }); 
    } 
} 
3

我知道的最簡單的方法是使用它自己的佈局管理器嵌套JPanel。

  • 主要的JPanel將使用BorderLayout的
  • 被添加到主處BorderLayout.SOUTH位置也使用的BorderLayout另一個JPanel的。
  • 需要在SE角落走的組件被添加到BorderLayout.EAST位置的上述JPanel。
  • 通常,使用佈局管理器與試圖設置組件的絕對位置幾乎總是比較好。
+0

是啊!我想設置JFrame。我爲我的誤會道歉!但謝謝你嘗試Pal! – Isuru 2012-03-17 21:52:41

+0

只要提到'BorderLayout.SOUTH'和'BorderLayout.EAST'的建議,當我們必須分別使用'BorderLayout.PAGE_END'和'BorderLayout.LINE_START'時,對於jdk 1.4+,參考[BorderLayout Tutorials ](http://docs.oracle.com/javase/tutorial/uiswing/layout/border.html):-) – 2012-03-18 08:43:09