我正在尝试在panelMain的左侧添加一个面板p1。由于对象不是垂直居中,我试图在p2上添加p1,它具有BorderLayout。我想这不是一个好方法,但它甚至不起作用。我没有使用GridLayout,因为我不希望对象填满整个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 :(得分:3)
“在JPanel中水平和垂直居中对象的最佳方法是什么”
您可以将所有内容打包在JPanel
中,然后将 JPanel
JPanel
包裹在另一个GridBagLayout
<{1}}
JPanel mainPanel = your main panel
JPanel wrapperPanel = new JPanel(new GridBagLayout());
wrapperPanel.add(mainPanel);
frame.add(wrapperPanel);
示例强>
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);
}
});
}
}