我试图在JLabel中强调文本,但根本没有任何工作

时间:2016-04-10 01:44:46

标签: java text jpanel jlabel underline

JLabel topCap = new JLabel ("  Top Caption");
txtTop = new JTextField("Enter top Caption here");
topCaption = new JLabel("", JLabel.CENTER);
viewerWindow.add(topCaption, BorderLayout.NORTH);
JLabel bottomCap = new JLabel ("  Bottom Caption");
txtBottom = new JTextField("Enter Bottom Caption here");
bottomCaption = new JLabel("",JLabel.CENTER);
viewerWindow.add(bottomCaption,BorderLayout.SOUTH);

我有另一段代码,当用户在JTextField中输入文本并按下更新JButton时,它会显示给JFrame。这适用于除下划线之外的所有样式(斜体和粗体)。我到处寻找,我在stackoverflow上找到了一段代码,但这对我们都没有帮助。如果你想知道,这是不起作用的代码行:

JLabel label = new JLabel("Underlined Label");
Font font = label.getFont();
Map attributes = font.getAttributes();
attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
label.setFont(font.deriveFont(attributes));

我很困惑有谁知道我应该怎么做? 或者至少我应该研究哪个班级? 感谢

2 个答案:

答案 0 :(得分:0)

您可以在JLabel中轻松使用HTML。举个例子,你可以这样做。

JLabel label=new JLabel();
label.setText("<html><u>Underlined Label</u></html>");

答案 1 :(得分:0)

您必须从awt

导入TextAttribute
java.awt.font.TextAttribute;

您可以使用HTML加下划线。但是为了比HTML更快的渲染,你应该坚持你的方法。

JLabel.setText("<HTML><U>Underlined Text</U></HTML>");