[英]Java how to preserve newline from String to JLabel?
JLabel newLabel = new JLabel();
String a = b;//b is String from database.
newLabel.setText(a);
I need to generate text pulled from my database which contains multiple line, but when i put them into the label, all of the text became same line. 我需要生成从包含多行的数据库中提取的文本,但是当我将它们放入标签时,所有文本都变成同一行。 I tried using JTextArea and it works, however, for some reason it messed with all the other component's alignment in a 1 column BoxLayout panel... which I wanted all the content to be aligned to the left.
我尝试使用JTextArea,但是它可以工作,但是由于某种原因,它使1列BoxLayout面板中的所有其他组件的对齐混乱了……我希望所有内容向左对齐。 Any help would be much appreciated!
任何帮助将非常感激! thanks
谢谢
however, for some reason it messed with all the other component's alignment in a 1 column BoxLayout panel
但是,由于某种原因,它使1列BoxLayout面板中所有其他组件的对齐方式混乱了
The is related to the setAlignmentX(...)
method of each component. 与每个组件的
setAlignmentX(...)
方法有关。
A JLabel uses 0.0f (for left alignment). JLabel使用0.0f(用于左对齐)。 A JTextArea and JScrollPane use 0.5f (for center alignment).
JTextArea和JScrollPane使用0.5f(用于中心对齐)。
Using components with different alignments will cause alignment issues when using a BoxLayout
. 当使用
BoxLayout
时,使用具有不同对齐方式的组件会导致对齐问题。
The solution is to change the alignment of the text area or scroll pane (whichever component you add to the BoxLayout). 解决方案是更改文本区域或滚动窗格(添加到BoxLayout的任何组件)的对齐方式。
So the basic code would be: 因此,基本代码为:
JLabel label = new JLabel(...);
JTextArea textArea = new JTextArea(...);
textArea.setAlignmentX(0.0f);
JPanel panel = new BoxLayout(...);
panel.add(label);
panel.add(textArea);
Now both components will be left aligned. 现在,两个组件将保持对齐。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.