我正在尝试在 JLabel 中为文本添加下划线,但没有任何效果

I'm trying to underline text in a JLabel but nothing is working at all

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。这适用于除下划线之外的所有样式(斜体和粗体)。我到处看了看,在 Whosebug 上找到了一段代码,但这也无济于事。如果您想知道,这是不起作用的代码行:

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));

我很困惑有人知道我应该做什么吗? 或者至少 class 我应该研究什么? 谢谢

您可以在 JLabel 中轻松使用 HTML。例如,您可以这样做。

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

您必须从 awt 导入 TextAttribute

java.awt.font.TextAttribute;

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

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