Reputation: 349
So in my GUI, I have a JFrame that's a borderlayout. There's a menubar, and some GUI stuff in NORTH and WEST. In CENTER, there is one JLabel. I want it to move to the center (both horizontally and vertically) of the JPanel. How do I do that correctly? I tried box layout and grid layout. One requirement is that I cannot use gridbag layout.
public class NewClass extends JFrame{
public NewClass () {
setVisible(true);
setSize(500,500);
setDefaultCloseOperation (EXIT_ON_CLOSE);
//menubar
JMenuBar bar = new JMenuBar();
JMenu editMenu = new JMenu("Edit");
JMenuItem mItem = new JMenuItem("Cut"); // edit->cut
editMenu.add(mItem);
mItem = new JMenuItem("Copy"); // edit->copy
editMenu.add(mItem);
mItem = new JMenuItem("Paste"); // edit->paste
editMenu.add(mItem);
bar.add(editMenu);
this.setJMenuBar(bar);
//north panel
JPanel topPanel = new JPanel();
this.add(topPanel,BorderLayout.NORTH);
JLabel myLabel = new JLabel ("Label:") ;
topPanel.add(myLabel);
JButton mytopButton = new JButton ("Push Me");
topPanel.add(mytopButton);
//left panel
JPanel leftPanel = new JPanel();
leftPanel.setBorder (new TitledBorder("Commands:"));
leftPanel.setLayout (new GridLayout (10,1));
this.add(leftPanel,BorderLayout.WEST);
JButton myLeftButton1 = new JButton ("Button 1");
leftPanel.add(myLeftButton1);
JButton myLeftButton2 = new JButton ("Button 2");
leftPanel.add(myLeftButton2);
JButton myLeftButton3 = new JButton ("Button3");
leftPanel.add(myLeftButton3);
//center panel
JPanel centerPanel = new JPanel();
this.add(centerPanel,BorderLayout.CENTER);
JLabel mapLabel = new JLabel("Test_String"); //move this to center of JPanel
centerPanel.add(mapLabel);
centerPanel.setBorder (new EtchedBorder(Color.black,Color.black));
centerPanel.setBackground (Color.white);
}
}
Upvotes: 0
Views: 4265
Reputation: 349
Answered. Thanks everyone.
JPanel centerPanel = new JPanel();
centerPanel.setLayout (new GridLayout ()); //added
this.add(centerPanel,BorderLayout.CENTER);
JLabel mapLabel = new JLabel("Test_String");
mapLabel.setHorizontalAlignment(SwingConstants.CENTER); //added
mapLabel.setVerticalAlignment(SwingConstants.CENTER); //added
centerPanel.add(mapLabel);
centerPanel.setBorder (new EtchedBorder(Color.black,Color.black));
centerPanel.setBackground (Color.white);
Upvotes: 1
Reputation: 347194
Start by taking a look at the JavaDocs for JLabel
Specifically, JLabel#setHorizontalAlignment
and JLabel#setVerticalAlignment
Upvotes: 1
Reputation: 324108
Check the API for methods that affect the alignment
of the component.
There are methods that affect the alignment of the component within the layout manager and others that affect the alignment of the text within the label itself.
Upvotes: 1