2012-11-04 123 views
3

我想和摆动这个接口:要使用哪种布局?

enter image description here

当我resise它,我希望所有的子面板和按钮调整大小是这样的:enter image description here

不仅主窗口被调整。我正在使用GridBagLayout。我不知道如何用GridBagLayout将面板的边框粘贴到框架的边框上,当我调整框架的大小时也要调整大小。

+1

有关显示你的码? – Simulant

回答

9

我通常为此使用嵌套布局。

  • BorderLayout为基数,使用JPanel
  • 将您的中央组件存储在JPanel中,并将其添加到BorderLayoutCENTER中。
  • 将您的底部组件存储在两个独立的JPanel s中。使用1行2列的GridLayout创建另一个JPanel
  • 以正确的顺序将两个JPanel添加到它。
  • 将此JPanel添加到BorderLayoutSOUTH
3

实现此目的的属性,即当JFrame被调整大小时,JPanel也应调整其本身,将是GridBagConstraints.BOTH。在我看来,你的左JButton是比右JButton有点小。如果你真的想与实现这一目标的GridBagLayout,在这里我已经制作了您的帮助下,小样本代码,看看,并要求任何可能出现的问题:

import java.awt.*; 
import javax.swing.*; 

public class GridBagExample 
{ 
    private JPanel contentPane; 

    private void displayGUI() 
    { 
     JFrame frame = new JFrame("GridBag Example"); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

     contentPane = new JPanel(); 
     contentPane.setLayout(new GridBagLayout()); 

     JPanel centerPanel = new JPanel(); 
     centerPanel.setOpaque(true); 
     centerPanel.setBackground(Color.CYAN); 

     GridBagConstraints gbc = new GridBagConstraints(); 
     gbc.anchor = GridBagConstraints.FIRST_LINE_START; 
     gbc.weightx = 1.0; 
     gbc.weighty = 0.9; 
     gbc.gridx = 0; 
     gbc.gridy = 0; 
     gbc.gridwidth = 2; 
     gbc.fill = GridBagConstraints.BOTH; // appears to me this is what you wanted 

     contentPane.add(centerPanel, gbc); 

     JButton leftButton = new JButton("Left"); 
     JButton rightButton = new JButton("Right"); 
     gbc.gridwidth = 1; 
     gbc.gridy = 1; 
     gbc.weightx = 0.3; 
     gbc.weighty = 0.1; 

     contentPane.add(leftButton, gbc); 

     gbc.gridx = 1; 
     gbc.weightx = 0.7; 
     gbc.weighty = 0.1; 

     contentPane.add(rightButton, gbc); 

     frame.setContentPane(contentPane); 
     frame.pack(); 
     frame.setLocationByPlatform(true); 
     frame.setVisible(true); 
    } 

    public static void main(String... args) 
    { 
     SwingUtilities.invokeLater(new Runnable() 
     { 
      @Override 
      public void run() 
      { 
       new GridBagExample().displayGUI(); 
      } 
     }); 
    } 
} 

GRIDBAGEXAMPLE OUTPUT :