【发布时间】:2014-12-10 04:39:54
【问题描述】:
我有一个JFrame 和一个JLabel,当我的程序运行时,我想通过setText() 更改JLabel 上的文本。我很清楚,为了在JLabel 中换行,必须在您希望换行的字符串周围放置<html> 标签,然后在标签内,还必须放置一个<br> 以便换行。
但是,我遇到了一个小问题。这是我的 MVCE。
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GearsWindow extends JFrame
{
public int x = 200;
public int y = 200;
public int speed = 5;
public String running;
public JLabel l;
public GearsWindow()
{
setSize(300, 200);
setLocation(x, y);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
l = new JLabel();
add(l);
running = "RUNNING";
updateLabel();
setVisible(true);
}
public static void main(String[] args)
{
GearsWindow gw = new GearsWindow();
}
public void updateLabel()
{
String result = running + "<html><br ></html>" + speedStatus();
l.setText(result);
}
public String speedStatus()
{
String result = "Speed - " + speed;
return result;
}
}
如果您要运行它,您最终会在JFrame 上得到如下所示的结果...
RUNNING<html><br></html>Speed - 5
现在,我知道最简单的方法是在每个String 周围添加<html> 标签,但是,由于我的程序将具有的复杂性,这将变得非常困难。我只是展示一个 MVCE,程序比这大得多。
是否可以使用方法或其他东西对字符串进行 HTML 化?
【问题讨论】:
-
Pahaha,原谅我,re不应该是速度之前的换行符 - 5,显然stackoverflow听我的代码,但不是我的实际应用程序
-
不要在html之外运行
-
跑步
速度 - 5 -
叫我疯了,但看起来你并没有关闭
<html>标签 - 你有两个开始标签。 -
字符串运行 = "RUNNING";字符串结果 = ""+ 运行 +"
"+speedStatus()+"" ; jLabel1.setText(结果);
标签: java html swing newline jlabel