Reputation: 1533
Here is my JPanel class. I have BoxLayout in it and only one JLabel added. My JLabel is on the left side of the screen. Is there any way to align all the components that are in the BoxLayout to the center. I tried this : setAlignmentX(CENTER_ALIGNMENT); but it doesnt work
public class MainPanel extends JPanel
{
// This layout we will use as our base layout.
private BoxLayout mainLayout = new BoxLayout(this, BoxLayout.Y_AXIS);
// This we will use to control padding in our main panel
EmptyBorder mainBorder = new EmptyBorder(10, 10, 10, 10);
private JLabel title = new JLabel("Podesavanja");
public MainPanel()
{
setLayout(mainLayout);
setBackground(Color.GRAY);
setAlignmentY(CENTER_ALIGNMENT);
// Setting padding
setBorder(mainBorder);
add(title);
}
// Dodajemo sve Ostale panele u ovu main panelu
public static void addPanel(JPanel panel)
{
addPanel(panel);
}
}
Upvotes: 0
Views: 197
Reputation: 324128
Is there any way to do it for all the elements inside layout ?
Not with a BoxLayout
. A BoxLayout
uses the alignment of individual components.
You can use different layout managers:
A GridBagLayout
will allow you to set the alignment by using a GridBagConstraint
. You set the alignment once and it will be used by all components. Of course you need to set the gridY of each component. So is this any different then setting the x alignment of the BoxLayout?
You can use a 3rd part layout manager like the the Relative Layout.
It works similar to a BoxLayout
in that you can layout components horizontally or vertically. However RelativeLayout
also allows you to specify alignment for the panel as a whole:
RelativeLayout rl = new RelativeLayout(RelativeLayout.Y_AXIS);
rl.setAlignment( RelativeLayout.CENTER );
JPanel panel = new JPanel( rl );
Upvotes: 2
Reputation: 691765
First of all, you call setAlignmentY()
instead of setAlignmentX()
. Second, you're calling it on the panel instead of calling it on the JLabel.
Fix those two bugs, and the label will be centered.
Upvotes: 2