While working on swing I face an issue with my JLabel on swing UI. I need to right a long text on a swing label and since the width of label was fixed, due to that some text is hiding and going outside of label area, So whole text on label was not being displayed. After some while I got the solution of problem by using html instead of plain text. Swing provides utility that support to display html on GUI. We can use html for showing labels anywhere in gui eg on JLabel, JButton, JTable Headers’ text etc
Following is the example that shows how to use HTML with swing components.
public class CustomJLabel {
JLabel label;
JFrame frame;
public CustomJLabel() {
frame = new JFrame("Custom JLabel with HTML style.");
label = new JLabel();
frame.setSize(250, 150);
frame.setPreferredSize(new Dimension(250, 150));
frame.setLocation(300, 200);
frame.getContentPane().add(BorderLayout.CENTER, label);
frame.setVisible(true);
frame.pack();
}
public static void main(String args[]) {
CustomJLabel customLabel = new CustomJLabel();
String text = "<html>This is the first line.<br/>"
+ "<div style='font-weight:normal;color:green;'>This is the second line.</div><br/>This is the third line.</html>";
customLabel.label.setText(text);
// customLabel.label.setAlignmentX(10.0f);
}
}
Related posts:


No Responses to “Customized Labels in swing GUI with HTML CSS”
Trackbacks/Pingbacks