JLabel with multiple lines and alignment to the right

我的未来我决定 提交于 2019-12-17 16:59:15

问题


I searched through many posts and figured out that JLabel supports HTML. So I can do

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

to get multiple lines. Above code will result in

Search  
By:  

However, What I want is something like

Search  
   By: 

Adding spaces before "By:" will work only when the window is not resizable(And very silly lol). Can anyone tell me how to modify this code to make it work as I wanted?


回答1:


Slightly simpler HTML than seen in @MadProgrammer's answer:

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



回答2:


There are a number of ways you might achieve this, one of the safer ways might be to use a <table> and aligning both cells to the right...

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

This overcomes issues with differences between fonts and font rendering on different platforms




回答3:


Non-breaking spaces (&nbsp;) are supported:

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

If you want to have real right-alignment, use individual right-aligned labels and combine them:

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

or use a read-only JTextPane instead (with \n for line breaks):

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


来源:https://stackoverflow.com/questions/29550524/jlabel-with-multiple-lines-and-alignment-to-the-right

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!