Search code examples
javaclassjlabel

Can someone explain how this works please?


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 have seen this code at least 100+ times today and i have tried it 100+ times and every single time it does not work. I am trying to underline text in a JLabel and this is the only block of code that i have found at all, and everyone else on stackoverflow seems to understand this, except me??? Is Map a class?


Solution

  • So, according to your question and comments, you have code somewhere that creates a JLabel named topCaption, adds it to a JPanel called viewWindow, and you can see the label as a results.

    So somewhere you have:

    JLabel topCaption = new JLabel( you may have some stuff here );
    

    Right after that, do this:

    Font font = topCaption.getFont();
    Map attributes = font.getAttributes();
    attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
    topCaption.setFont(font.deriveFont(attributes));
    

    Also, I might suggest you need to do more reading before you continue with this, as knowledge of what a Map is, etc. is pretty basic to most UI programming, and you're going to continue to have trouble like this without some fundamentals under your belt.