So I have got round to creating a panel that has two labels and a button inside and these are alligned on the Y_axis via a box layout.
I am now trying to get it so that the text is alligned to the centre of the panel as well as on the Y axis for neatness.
Here is the code I have right now:
JPanel statPanel = new JPanel();
statPanel.setBorder(BorderFactory.createTitledBorder("Text Statistics"));
statPanel.add((averageLength = new JLabel("The average length of the words: ")));
statPanel.add((totalWords = new JLabel("The total number of words: ")));
//Create button inside statPanel
statPanel.add((stats = new JButton("Update Text Statistics")));
stats.addActionListener(new ButtonListener());
statPanel.setOpaque(false);
statPanel.setLayout(new BoxLayout(statPanel, BoxLayout.Y_AXIS));
As you can see I have already used BoxLayout in order to get the vertical alignment and I have tried the following code which didnt seem to affect my situation at all (and did seem very long winded):
averageLength.setHorizontalAlignment(SwingConstants.CENTER);
averageLength.setVerticalAlignment(SwingConstants.CENTER);
totalWords.setHorizontalAlignment(SwingConstants.CENTER);
totalWords.setVerticalAlignment(SwingConstants.CENTER);
stats.setHorizontalAlignment(SwingConstants.CENTER);
stats.setVerticalAlignment(SwingConstants.CENTER);
If you could advise me that would be much appreciated! Thanks
You don't need to set the horizontal or vertical alignment. Those properties are used with a layout manager (ie BorderLayout) that changes the size of the component to be something greater than the preferred size of the component. Then the component aligns the text based on its painting rules.
Instead, you need to set the x alignment. In this case the component size is still the preferred size. However, the layout manager aligns the component to the space available in the container. So to center the component in the width of the container you would use:
averageLength.setAlignmentX(0.5f);
totalWords.setAlignmentX(0.5f);
stats.setAlignmentX(0.5f);
The BoxLayout doesn't change the size of the component so it respects this property.