Hurdler Hurdler - 1 year ago 65
Java Question

How to center the text in a JLabel?

despite many tries I can't get the result that I would like to see - text centered within the JLabel and the JLabel somewhat centered in the BorderLayout. I said "somewhat" because there should be also another label "status" in the bottom-right corner of the window. Here the bit of code responsible for that:

setLayout(new BorderLayout());
JPanel area = new JPanel();
JLabel text = new JLabel(
"<html>In early March, the city of Topeka," +
" Kansas,<br>temporarily changed its name to Google..." +
"<br><br> an attempt to capture a spot<br>" +
"in Google's new broadband/fiber-optics project." +
"<br><br><br>source:" +
"#Oil_Tanker_Data_Center</html>", SwingConstants.CENTER);
JLabel status = new JLabel("status", SwingConstants.SOUTH_EAST);
Font font = new Font("SansSerif", Font.BOLD, 30);
// text.setAlignmentX(CENTER_ALIGNMENT);
// text.setAlignmentY(CENTER_ALIGNMENT);
// text.setHorizontalAlignment(JLabel.CENTER);
// text.setVerticalAlignment(JLabel.CENTER);
Font font2 = new Font("SansSerif", Font.BOLD, 20);
area.add(text, BorderLayout.CENTER);
area.add(status, BorderLayout.EAST);

Thanks for any help provided.

Answer Source
String text = "In early March, the city of Topeka, Kansas," + "<br>" +
              "temporarily changed its name to Google..." + "<br>" + "<br>" +
              " an attempt to capture a spot" + "<br>" +
              "in Google's new broadband/fiber-optics project." + "<br>" + "<br>" +"<br>" +
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</html>");