【问题标题】:JLabel with multiple lines and alignment to the right具有多行并向右对齐的 JLabel
【发布时间】:2015-06-15 12:41:20
【问题描述】:

我搜索了很多帖子,发现JLabel 支持 HTML。 这样我就可以了

JLabel search  = new JLabel("<html>Search<br/> By:</html>");

获取多行。上面的代码会导致

Search  
By:  

但是,我想要的是类似

Search  
   By: 

在“By:”之前添加空格仅在窗口不可调整大小时才有效(而且非常愚蠢的哈哈)。 谁能告诉我如何修改此代码以使其按我的意愿工作?

【问题讨论】:

    标签: java html swing jlabel


    【解决方案1】:

    支持不间断空格 (&amp;nbsp;):

    new JLabel("<html>Search<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; By:</html>");
    

    如果您想要真正的右对齐,请使用单独的右对齐标签并将它们组合起来:

    JLabel search = new JLabel("Search", SwingConstants.RIGHT);
    JLabel by = new JLabel("By:", SwingConstants.RIGHT);
    
    JPanel combined = new JPanel();
    combined.setOpaque(false);
    combined.setLayout(new GridLayout(2, 1));
    combined.add(search);
    combined.add(by);
    

    或者使用只读的JTextPane 代替(使用\n 换行):

    JTextPane text = new JTextPane();
    
    SimpleAttributeSet attributes = new SimpleAttributeSet();
    StyleConstants.setAlignment(attributes, StyleConstants.ALIGN_RIGHT);
    StyleConstants.setFontFamily(attributes, "Default");
    text.setParagraphAttributes(attributes, true);
    text.setEditable(false);
    text.setOpaque(false);
    text.setText("Search\nBy:");
    

    【讨论】:

      【解决方案2】:

      您可以通过多种方式实现此目的,其中一种更安全的方法可能是使用 &lt;table&gt; 并将两个单元格向右对齐...

      JLabel label = new JLabel(
                      "<html><table border='0' cellpadding='0' cellspacing='0'>" + 
                                      "<tr><td align='right'>Search</td></tr>" +
                                      "<tr><td align='right'>By:</td></tr></table>"
      );
      

      这克服了不同平台上字体和字体渲染之间存在差异的问题

      【讨论】:

        【解决方案3】:

        比@MadProgrammer 的回答中看到的稍微简单的 HTML:

        new JLabel("<html><body style='text-align: right'>Search<br>By:");
        

        【讨论】:

        • "div" 也很好用:new JLabel("
          Search
          By:
          " );
        猜你喜欢
        • 2011-11-25
        • 2012-09-17
        • 2018-05-08
        • 2012-08-15
        • 2011-02-25
        • 1970-01-01
        • 1970-01-01
        • 2019-11-17
        • 1970-01-01
        相关资源
        最近更新 更多