javahtmlswingjlabelcenter-align

Text Not Aligning To the Center of JLabel in Java


I have a JLabel on the bottom of my panel that gives text instructions to the user. Some of the text went off the screen because it was too long. To fix this, I added tags. However, now the text is no longer centered, it is now aligned to the left. Why is this case. Shouldn't this code center the text?

detailedInstructions.setText("<html><div align=center>" + test.getMicroSteps()[currMicroStep].getDescription() + "</div><html>");

Solution

  • Instead of using HTML code, simply call

    detailedInstructions.setHorizontalAlignment(SwingConstants.CENTER);
    

    Or use the JLabel constructor that sets the horizontal alignment.

    Note that if the JLabel displays an ImageIcon, then you'll also want to set it's horizontal text position which determines the location of the label's text relative to its image.

    Other potential issues is that the JLabel itself might not be centered at teh bottom of the GUI. To test this, put a border around the label to see it's actual placement, and if so, then you will need to work with the settings of the label's container's layout manager.