Reputation: 81
I'm trying to add a panel p1 on the left on the panelMain. Since the objects are not center vertically, I tried to add p1 on p2, which has BorderLayout. I guess this is not a good way but it doesn't even work. I didn't use GridLayout because I don't want the objects to fill up the whole 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 );
Upvotes: 1
Views: 3477
Reputation: 209132
"What is best way to center objects in JPanel horizontally and vertically"
You can wrap everything in JPanel
then wrap that JPanel
in another JPanel
with a GridBagLayout
JPanel mainPanel = your main panel
JPanel wrapperPanel = new JPanel(new GridBagLayout());
wrapperPanel.add(mainPanel);
frame.add(wrapperPanel);
Example
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);
}
});
}
}
Upvotes: 3