PROGRAMMING

m9/ JAVA
REMEMBERS




Last update:   26-07-2021

JLabel

! With the JLabel you can display unselectable text and images. Use font attributes to set JLabel underline.
 
import java.awt.*;
import java.awt.font.TextAttribute;
import java.util.Map;
import javax.swing.*;

public class App extends JFrame {

    public static void main(String[] args) {
    
        App frame = new App();
    
        frame.setBounds(200, 200, 300, 200);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    
    public App() {

        JLabel label = new JLabel("Underlined Label");
        Font font = label.getFont();
        Map attributes = font.getAttributes();

            // Look Here
        attributes.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_ON);
        //attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_REGULAR);
        //attributes.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);

        label.setFont(font.deriveFont(attributes));
        
        JPanel panel = new JPanel();
        panel.add(label);
        
        add(panel);
    }
}
... 19 lines
 

Border

We can set a border to label using setBorder() method.
 
import java.awt.*;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class App extends JFrame {

    public static void main(String[] args) {
        JFrame frame = new App();
        frame.setBounds(200, 200, 300, 200);
        frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public App() {
        
        JLabel label = new JLabel("my text"); // Look Here
        label.setBorder(BorderFactory.createLineBorder(Color.red));
        JPanel panel = new JPanel();
        panel.add(label);
        add(panel);
        
        // Outputs: a label with red border
    }
}
... 15 lines
 

Questions    
Image