如何将文本置于JLabel中心?

尽管经过多次尝试,但我无法得到我希望看到的结果 – 在JLabel中居中的文本和JLabel在BorderLayout中居中。 我说“有点”,因为窗口的右下角应该还有另一个标签“status”。 这里有一些代码负责:

setLayout(new BorderLayout()); JPanel area = new JPanel(); JLabel text = new JLabel( "In early March, the city of Topeka," + " Kansas,
temporarily changed its name to Google..." + "

...in an attempt to capture a spot
" + "in Google's new broadband/fiber-optics project." + "


source: http://en.wikipedia.org/wiki/Google_server" + "#Oil_Tanker_Data_Center", 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);

感谢您提供的任何帮助。

 String text = "In early March, the city of Topeka, Kansas," + "
" + "temporarily changed its name to Google..." + "
" + "
" + "...in an attempt to capture a spot" + "
" + "in Google's new broadband/fiber-optics project." + "
" + "
" +"
" + "source: http://en.wikipedia.org/wiki/Google_server#Oil_Tanker_Data_Center"; JLabel label = new JLabel("
" + text + "
");

以下构造函数JLabel(String, int)允许您指定标签的水平对齐方式。

 JLabel label = new JLabel("The Label", SwingConstants.CENTER); 
 myLabel.setHorizontalAlignment(SwingConstants.CENTER); myLabel.setVerticalAlignment(SwingConstants.CENTER); 

如果由于某种原因无法重建标签,则可以使用以下方法编辑预先存在的JLabel的这些属性。

Interesting Posts