问题
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 (
) are supported:
new JLabel("<html>Search<br/> 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