2012-02-29 100 views
0

是否可以在使用AbsoluteLayout的JFrame的边缘周围留出一些额外的空间?当我有一个按钮作为JFrame上最下面的组件时,它将被定位在JFrame窗口的底部边缘上,并且看起来很糟糕。我想知道是否有一种方法可以在使用AbsoluteLayout时在组件和JFrame的边缘之间添加一些额外的空间。Java:AbsoluteLayout中的额外空间

+0

AbsoluteLayout实际上没有布局 - 不要使用它 – kleopatra 2012-03-01 12:43:45

回答

0

您可以使用Box.createRigidArea(尺寸)创建一个可以在按钮下方添加的空白空间。

2

建议:

  • 当你将组件添加到一个JFrame,你实际上是将它添加到JFrame的contentPane中。为了给contentPane一个“缓冲区”边界,考虑给它一个EmptyBorder(...),参数是int常量,用于组件周围所需的边界量。
  • 避免对任何东西使用“绝对”布局,特别是将组件放置在布局管理器的易放置位置(例如GUI底部)。

例如,记在下面如何中部,底部JPanel的不走出去的GUI的边缘,因为空边框的代码创建的GUI:

import java.awt.BorderLayout; 
import java.awt.Dimension; 

import javax.swing.*; 

public class ButtonAtBottom { 
    private static void createAndShowGui() { 
     JPanel bottomPanel = new JPanel(); 
     bottomPanel.add(new JButton("Bottom Button")); 
     bottomPanel.setBorder(BorderFactory.createTitledBorder("Bottom Panel")); 

     JPanel centerPanel = new JPanel(); 
     centerPanel.setBorder(BorderFactory.createTitledBorder("Center Panel")); 


     JPanel mainPanel = new JPanel(new BorderLayout()); 
     mainPanel.add(centerPanel, BorderLayout.CENTER); 
     mainPanel.add(bottomPanel, BorderLayout.PAGE_END); 

     // **** here I add the border to the mainPanel which I'll 
     // make into the contentPane 
     int eb = 25; 
     mainPanel.setBorder(BorderFactory.createEmptyBorder(eb, eb, eb, eb)); 

     // don't set the preferredSize per Kleopatra, but am doing it 
     // here simply to make code shorter for this sscce 
     mainPanel.setPreferredSize(new Dimension(500, 400)); 

     JFrame frame = new JFrame("ButtonAtBottom"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setContentPane(mainPanel); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      createAndShowGui(); 
     } 
     }); 
    } 
} 
+1

大声咧嘴笑:-) – kleopatra 2012-03-01 12:43:00

0

设置一个您的内容面板上的空白边框,其中SIZE是您需要的填充量。

JFrame frame = new JFrame(); 
JPanel panel = new JPanel(null); 
panel.setBorder(BorderFactory.createEmptyBorder(SIZE,SIZE,SIZE,SIZE); 
frame.setContentPane(panel); 
//The rest 

的参数是为上,左,下,右填充,所以如果你想在每一个边缘不同垫衬,可以进行相应的设置。