Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center elements in the BoxLayout using center of the element?

I use outputPanel.setLayout(new BoxLayout(outputPanel, BoxLayout.Y_AXIS)); and then I add elements (for example JLabels, JButtons) to the outputPanel. For example: outputPanel.add(submitButton);.

I see that all added elements are "centered". It is good, because I do want my elements to be in the center. When I write "center" I mean "equal distance from left and right". But the problem is that the left part of the element is put into the center. And I want to have center of elements to be put into the center. How can I get this behavior?

like image 726
Roman Avatar asked Apr 01 '10 13:04

Roman


People also ask

How do I center an element in a JFrame?

game. setLocationRelativeTo(null); and your JFrame game will be placed in the center of the screen.

How do you center an object in Java?

add(panel, BorderLayout. CENTER);

What is box layout in Java?

public class BoxLayout extends Object implements LayoutManager2, Serializable. A layout manager that allows multiple components to be laid out either vertically or horizontally. The components will not wrap so, for example, a vertical arrangement of components will stay vertically arranged when the frame is resized.

How do you make a button grid in Java?

To create a new frame you type: JFrame frame = new JFrame(); Inside the constructor method we need to make sure that all of the buttons are put in the grid layout. To do this we set the layout of frame by typing: frame. setLayout(new GridLayout(x, y));


1 Answers

The problem can be solved by using myLabel.setAlignmentX(Component.CENTER_ALIGNMENT);. It works with JLabel, JButton and JRadioButton.

like image 94
Roman Avatar answered Oct 08 '22 10:10

Roman