我正在尝试从项目中名为 Circle 的类调用一个方法,该方法显示有关 JLabel 中对象的一些基本信息。由于某种原因,即使我使用 HTML 尝试设置文本格式,文本也不会换行:
@Override
public String toString(){
return "<html>Type: " + this.getClass().getSimpleName() + "<br>Radius: " + getRadius() + "<br>Area: " + df.format(getArea()) + "<br>Perimeter: </html>" + df.format(getPerimeter());
}
我正在尝试使用以下代码显示信息:
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==btnCalc && x==1){
//create object
double R = Double.parseDouble(Txt1.getText());
Circle circ = new Circle(R);
lblResult.setText(circ.toString());
}
当我运行该程序时,它只返回:<html>Type: Circle<br>Radius: 4.0<br>Area: 50.27<br>Perimeter:</html> 25.13
编辑:我尝试将文本设置为异常消息,而不是调用该方法,但这种方式也不起作用 编辑:现在,当我尝试运行圆柱体球体类时,会发生这种情况,但当我在 toString() 方法中没有任何 html 时,它不会执行此操作。
事实证明,我在最后四个类中使用了 DecimalFormat,这就是给我带来异常的原因。一旦我摆脱了这个问题,字符串就可以使用 JTextPane 而不是 JtextField 很好地格式化。
最佳答案
从您粘贴的图像来看,它看起来像是一个文本 INPUT 控件(在 Show Info
按钮下),类似于 JTextField
而不是一个JLabel
。
您也可以将 HTML
内容与 JLabel
构造函数及其 setText
方法一起使用。效果很好。
JLabel lbl = new JLabel("<html>Type: Circle<br>Some info<br>More info</html>")
JLabel lbl2 = new JLabel();
lbl2.setText("<html>Type: Circle<br>Some info<br>More info</html>")
但是,如果您想要一个 INPUT 控件(如您的图像中所示),则不能将 HTML
与 JTextField
一起使用。为此,您必须使用 JTextPane
。
JTextPane txt = new JTextPane();
txt.setContentType("text/html");
txt.setText("<html>Type: Circle<br>Some info<br>More info</html>");
关于java - JLabel HTML 换行问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26359679/