2014-03-01 177 views
1

我試圖在panelMain的左側添加一個面板p1。由於對象不是垂直居中,我試圖在p2上添加p1,該p2具有BorderLayout。我想這不是一個好方法,但它甚至不起作用。我沒有使用GridLayout,因爲我不想讓對象填滿整個JPanel。什麼是在JPanel水平和垂直居中對象的最佳方式

JPanel panelMain = new JPanel(new BorderLayout()); 

JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER)); 
panelText.setPreferredSize(new Dimension(250, frame.getHeight())); 
panelText.add(new JLabel("Name:", SwingConstants.RIGHT)); 
panelText.add(new JTextField("First Last:", 15)); 
panelText.add(new JLabel(" Tel:", SwingConstants.RIGHT)); 
panelText.add(new JTextField("000-000-0000", 15)); 

JPanel p2 = new JPanel(new BorderLayout()); 
p2.add(p1, BorderLayout.CENTER); 

panelMain.add(p2,BorderLayout.WEST); 
+0

,什麼是出把你得到了什麼? –

+0

請參閱[本答案](http://stackoverflow.com/a/16727593/418556)兩種佈局('GridBagLayout'或'BoxLayout'),它們將以組件或容器爲中心。 –

回答

3

「什麼是在JPanel的水平和垂直居中的對象最好的辦法」

可以在JPanel包裹一切然後包在另一個JPanelJPanelGridBagLayout

JPanel mainPanel = your main panel 
JPanel wrapperPanel = new JPanel(new GridBagLayout()); 
wrapperPanel.add(mainPanel); 
frame.add(wrapperPanel); 

enter image description here

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

public class TestCenterGridbagLayout { 
    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable(){ 
      public void run() { 
       JPanel mainPanel = new JPanel(new GridLayout(3, 3)); 
       for (int i = 0; i < 9; i++) { 
        mainPanel.add(new JButton("Button")); 
       } 
       mainPanel.setBorder(new TitledBorder("Main Panel")); 

       JPanel wrapperPanel = new JPanel(new GridBagLayout()); 
       wrapperPanel.setPreferredSize(new Dimension(350, 300)); 
       wrapperPanel.add(mainPanel); 
       wrapperPanel.setBorder(new TitledBorder("Wrapper panel with GridbagLayout")); 

       JOptionPane.showMessageDialog(null, wrapperPanel); 

      } 
     }); 
    } 
}