Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>...in an attempt to capture a spot<br>" +         "in Google's new broadband/fiber-optics project." +         "<br><br><br>source: http://en.wikipedia.org/wiki/Google_server" +         "#Oil_Tanker_Data_Center</html>", SwingConstants.CENTER); text.setVerticalAlignment(SwingConstants.CENTER); JLabel status = new JLabel("status", SwingConstants.SOUTH_EAST); status.setVerticalAlignment(SwingConstants.CENTER); Font font = new Font("SansSerif", Font.BOLD, 30); text.setFont(font); area.setBackground(Color.darkGray); text.setForeground(Color.green); // text.setAlignmentX(CENTER_ALIGNMENT); // text.setAlignmentY(CENTER_ALIGNMENT); // text.setHorizontalAlignment(JLabel.CENTER); // text.setVerticalAlignment(JLabel.CENTER); Font font2 = new Font("SansSerif", Font.BOLD, 20); status.setFont(font2); status.setForeground(Color.green);       area.add(text, BorderLayout.CENTER);         area.add(status, BorderLayout.EAST); this.add(area); 

Thanks for any help provided.

like image 752
Hurdler Avatar asked Jul 25 '11 00:07

Hurdler


People also ask

How do I change the alignment of a JLabel?

This can be done in two ways. To align to the right: JLabel label = new JLabel("Telephone", SwingConstants. RIGHT);

How do I center align text in Java GUI?

setAlignmentY(CENTER_ALIGNMENT); // text. setHorizontalAlignment(JLabel. CENTER); // text. setVerticalAlignment(JLabel.

How do I center text in Jtextfield?

Just use the setBounds attribute. Jtextfield. setBounds(x,x,x,x);


1 Answers

The following constructor, JLabel(String, int), allow you to specify the horizontal alignment of the label.

JLabel label = new JLabel("The Label", SwingConstants.CENTER); 
like image 115
nimmi Avatar answered Sep 28 '22 04:09

nimmi