Search code examples
javatextjpaneljlabelunderline

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

I have another block of code in which when the user enters text into the JTextField, and presses the update JButton it is displayed to the JFrame. This works fine for all styles (italic and bold) except underline. I've looked everywhere and I found a block of code on stackoverflow but that didn't help either. In case you're wondering, this is the line of code that didn't work:

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

I am thoroughly confused does anyone know what i should do? Or at least what class i should look into? thanks


Solution

  • You must import TextAttribute from awt

    java.awt.font.TextAttribute;
    

    You can use HTML to underline. But for faster rendering than HTML, you should stick to your method.

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