46

尽管进行了多次尝试,但我无法获得我希望看到的结果 - 文本以 JLabel 为中心,而 JLabel 有点以 BorderLayout 为中心。我说“有点”是因为窗口的右下角还应该有另一个标签“状态”。这里有一段代码负责:

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

感谢您提供的任何帮助。

4

3 回答 3

125

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

JLabel label = new JLabel("The Label", SwingConstants.CENTER);
于 2013-08-02T03:35:17.917 回答
43
myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

如果由于某种原因无法重建标签,这就是您编辑预先存在的 JLabel 的这些属性的方式。

于 2014-02-07T21:53:33.140 回答
33
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>");
于 2011-07-25T00:02:59.060 回答