Java 通过设置最大宽度使 JLabel 包裹它的文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2420742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
make a JLabel wrap it's text by setting a max width
提问by Aly
I have a JLabel which has a lot of text on it. Is there a way to make the JLabel have a max width so that it will wrap the text to make it not exceed this width?
我有一个 JLabel,上面有很多文字。有没有办法让 JLabel 具有最大宽度,以便它包裹文本以使其不超过此宽度?
Thanks
谢谢
采纳答案by camickr
No.
不。
You can use HTML in the label, but then you must hard code the break tag.
您可以在标签中使用 HTML,但是您必须对 break 标记进行硬编码。
A better approach is to use a JTextArea and turn wrapping on. You can change the background,foreground, font etc. of the text are to make it look like a label.
更好的方法是使用 JTextArea 并打开环绕。您可以更改文本的背景、前景、字体等,使其看起来像一个标签。
Note, this answer is outdated as of at least Java 7.
请注意,此答案至少在 Java 7 中已过时。
As per @darren's answer, you simply need to wrap the string with <html>
and </html>
tags:
根据@darren 的回答,您只需要用<html>
和</html>
标签包装字符串:
myLabel.setText("<html>"+ myString +"</html>");
You do not need to hard-code any break tags. The text wraps as the component resizes.
您不需要硬编码任何中断标记。当组件调整大小时,文本会换行。
回答by Alexander.Berg
Yes there are two similar ways (first with css style="width:...px", second with html WIDTH=.......:
是的,有两种类似的方式(第一个使用 css style="width:...px",第二个使用 html WIDTH=.......:
1.
1.
labelText = String.format("<html><div style=\"width:%dpx;\">%s</div></html>", width, text);
2.
2.
labelText = String.format("<html><div WIDTH=%d>%s</div></html>", width, text);
回答by Sam Barnum
There's a good technique here, scroll to the end of the article.
有一个很好的技术在这里,滚动到文章的末尾。
JLabel labelBeingUsed = myLabel;
View view = (View) labelBeingUsed.getClientProperty(BasicHTML.propertyKey);
view.setSize(scrollPane1.getWidth(), 0.0f);
float w = view.getPreferredSpan(View.X_AXIS);
float h = view.getPreferredSpan(View.Y_AXIS);
labelBeingUsed.setSize((int) w, (int) h);
回答by darren
or simply use
或者干脆使用
myLabel.setText("<html>"+ myString +"</html>");
回答by kleopatra
JXLabel in the SwingX projectsupports wrapping
SwingX项目中的JXLabel支持换行
JXLabel label = new JXLabel(somelongtext);
label.setLineWrap(true);
回答by demBones
You can use HTML without hard coding break tags if you use paragraph tags instead.
如果您改用段落标记,则可以使用 HTML 而不使用硬编码中断标记。
JLabel biglabel = new JLabel("<html><p>A lot of text to be wrapped</p></html>");
回答by Andrei Vajna II
Other than wrapping the text in <html>
tags, you also have to put the label into a container that respects the preferred height and sets the width to maximum. For example, you can put the label in to the NORTH of a BorderLayout
.
除了将文本包裹在<html>
标签中之外,您还必须将标签放入符合首选高度并将宽度设置为最大的容器中。例如,您可以将标签放在 a 的 NORTH 中BorderLayout
。
Here is a simple but complete working program to illustrate this. You can resize the frame in any way you want; the label will occupy the whole width and the height will adjust accordingly to wrap the text. Notice that all that I'm doing is using <html>
tags and putting the label in the NORTH of the BorderLayout
.
这是一个简单但完整的工作程序来说明这一点。你可以以任何你想要的方式调整框架的大小;标签将占据整个宽度,高度将相应地调整以包裹文本。请注意,我所做的只是使用<html>
标签并将标签放在BorderLayout
.
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.JPanel;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Dimension;
public class LabelWrap {
public static JPanel createPanel() {
JLabel label = new JLabel();
label.setText("<html>"
+ "<h3>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</h3>"
+ "<p>Duis a tincidunt urna. Phasellus tristique interdum mauris, "
+ "ut vestibulum purus suscipit eget. Aenean massa elit, accumsan "
+ "non faucibus vel, dictum placerat urna. In bibendum est sagittis "
+ "urna iaculis quis sagittis velit commodo. Cum sociis natoque "
+ "penatibus et magnis dis parturient montes, nascetur ridiculus "
+ "mus. Nam quis lacus mauris. Phasellus sem libero, convallis "
+ "mattis sagittis vel, auctor eget ipsum. Vivamus molestie semper "
+ "adipiscing. In ac neque quis elit suscipit pharetra. Nulla at "
+ "orci a tortor consequat consequat vitae sit amet elit. Praesent "
+ "commodo lacus a magna mattis vehicula. Curabitur a hendrerit "
+ "risus. Aliquam accumsan lorem quis orci lobortis malesuada.</p>"
+ "<p>Proin quis viverra ligula. Donec pulvinar, dui id facilisis "
+ "vulputate, purus justo laoreet augue, a feugiat sapien dolor ut "
+ "nisi. Sed semper augue ac felis ultrices a rutrum dui suscipit. "
+ "Praesent et mauris non tellus gravida mollis. In hac habitasse "
+ "platea dictumst. Vestibulum ante ipsum primis in faucibus orci "
+ "luctus et ultrices posuere cubilia Curae; Vestibulum mattis, "
+ "tortor sed scelerisque laoreet, tellus neque consectetur lacus, "
+ "eget ultrices arcu mi sit amet arcu. Nam gravida, nulla interdum "
+ "interdum gravida, elit velit malesuada arcu, nec aliquam lectus "
+ "velit ut turpis. Praesent pretium magna in nibh hendrerit et "
+ "elementum tellus viverra. Praesent eu ante diam. Proin risus "
+ "eros, dapibus at eleifend sit amet, blandit eget purus. "
+ "Pellentesque eu mollis orci. Sed venenatis diam a nisl tempor "
+ "congue.</p>"
+ "</html>");
JPanel panel = new JPanel(new BorderLayout());
panel.add(label, BorderLayout.NORTH);
panel.setPreferredSize(new Dimension(640, 480));
return panel;
}
/**
* @param args
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(createPanel());
frame.pack();
frame.setVisible(true);
}
});
}
}
回答by Rajj
If you only want to use JLabel than you can try this approach,
如果您只想使用 JLabel,则可以尝试这种方法,
just display the number of characters you want to display on label using substring method.
只需使用子字符串方法显示要在标签上显示的字符数。
public void setLabel(String label){
String dispLabel=label.substring(0, numOfCharacter);
labelComponent.setText(dispLabel);
}
回答by Jeff_Alieffson
<html>
wrapping works but not in all cases. If the parent container uses FlowLayout then it'll not work. Therefore I set it to BoxLayout. Look at this code snippet:
<html>
包装工作,但并非在所有情况下。如果父容器使用 FlowLayout,那么它将不起作用。因此我将其设置为 BoxLayout。看看这个代码片段:
javax.swing.JPanel pRefundNote = new javax.swing.JPanel();
javax.swing.JLabel lbNote = new javax.swing.JLabel();
pRefundNote.setAlignmentX(0.0F);
pRefundNote.setMaximumSize(new java.awt.Dimension(32767, 33));
pRefundNote.setLayout(new javax.swing.BoxLayout(pRefundNote, javax.swing.BoxLayout.X_AXIS));
lbNote.setText("<html>Select items using Shift or Ctrl and Up/Down keys or Mouse</html>");
lbNote.setVerticalAlignment(javax.swing.SwingConstants.TOP);
lbNote.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
pRefundNote.add(lbNote);
Don't add <br>
because it'll break your text even if you enlarge your parent frame and pRefundNote container.
不要添加,<br>
因为即使您放大父框架和 pRefundNote 容器,它也会破坏您的文本。