如何将文本置于JLabel中心?

时间:2011-07-25 00:00:38

标签: java swing user-interface jlabel htmltext

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

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);

感谢您提供的任何帮助。

3 个答案:

答案 0 :(得分:86)

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

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

答案 1 :(得分:33)

myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

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

答案 2 :(得分:29)

String text = "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";
JLabel label = new JLabel("<html><div style='text-align: center;'>" + text + "</div></html>");