Dragneel
Dragneel

Reputation: 181

JLabel not displaying HTML correctly

This question is a follow up from my previous question

I have a JLabel with HTML text inside it. However, the HTML content it is not being displayed correctly. The JLabel is supposed to be 26x26 pixels with a number being displayed at the bottom right. My code doesn't seem to be displaying the number in the correct position, and its height seems to be truncated.

Here is my code:

final String buffBadgeStyles = "<style>" 
+ "#container {height:26px; width:26px; background-color: red; position:relative;}" 
+ "#bottom {position:absolute; bottom:0; right:0;}" 
+ "</style>";

buffSlot_6 = new JLabel();
buffSlot_6.setBorder(new LineBorder(Color.BLACK));
buffSlot_6.setHorizontalAlignment(SwingConstants.CENTER);
buffSlot_6.setVerticalAlignment(SwingConstants.CENTER);
buffSlot_6.setText("<html>" 
+ buffBadgeStyles 
+ "<body>" 
+ "<p id=\"container\"><span id=\"bottom\">2</span></p>" 
+ "</body></html>");
buffSlot_6.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
panel_playerBuffs.add(buffSlot_6);

The JLabel is meant to look something like this enter image description here But my code is generating this enter image description here

Any thoughts?

Upvotes: 0

Views: 575

Answers (1)

guleryuz
guleryuz

Reputation: 2734

you can get this view by using a helper panel (that is wrapping the label) and choosing a proper layout for the panel. This way you don't need html. You should set 26 px size to the wrapping panel instead of label.

package so;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.LineBorder;

public class Main {

    public static void main(String[] args) {

        SwingUtilities.invokeLater( () -> {

            JFrame frame = new JFrame("Label test");

            JPanel helperPanel = new JPanel();

            frame.setContentPane(helperPanel);
            helperPanel.setLayout(new BorderLayout());

            JLabel buffSlot_6 = new JLabel();
            buffSlot_6.setBorder(new LineBorder(Color.BLACK));
            buffSlot_6.setHorizontalAlignment(SwingConstants.RIGHT);
            buffSlot_6.setVerticalAlignment(SwingConstants.BOTTOM);
            buffSlot_6.setText("2");

            buffSlot_6.setFont(new Font("Comic Sans MS", Font.BOLD, 12));
            helperPanel.add(buffSlot_6, BorderLayout.CENTER);

            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLocationRelativeTo(null);
            frame.setSize(100, 100);
            frame.setVisible(true);

        } );
    }
}

Upvotes: 3

Related Questions