2012-03-17 68 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

相关问题