2012-02-29 98 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 

的參數是爲上,左,下,右填充,所以如果你想在每一個邊緣不同墊襯,可以進行相應的設置。