FareJump
FareJump

Reputation: 113

Java swing, JLabel with html text not rendering properly on hovers

I've come across this wierd interaction with my JLabel and html. If I use html in the string for the jlabel constructor and I hover over the JLabel it'll mess up my entire JPanel, putting everything up on one line and not respecting any bounds made to the components. But if I just use a simple string like "test", the hover effect works correctly.

The mouse enter and exit just brightens the color and puts it back again on exit.

text = "someString";
JPanel jp = new JPanel();

String str = "<html><div color='red'><u>"+text+"</u></div></html>";
JLabel jl = new JLabel(str);
jl.addMouseListener(this);
jp.add(jl);


@Override
public void mouseEntered(MouseEvent e) {
    JLabel jl = (JLabel) e.getSource();
    currentJlColor = jl.getForeground();
    jl.setForeground(Color.decode("#c0c0c0"));
}

@Override
public void mouseExited(MouseEvent e) {
    JLabel jl = (JLabel) e.getSource();
    jl.setForeground(currentJlColor);
}

Upvotes: 1

Views: 497

Answers (1)

NoddySevens
NoddySevens

Reputation: 94

When you are passing HTML formatted text you can not change the formatting of that text using the standard java library.

One possible work around would be to create strings with different formats as you need them and use the SetText method to change the JLabel

text = "someString";
JPanel jp = new JPanel();

String str1 = "<html><div color='red'><u>"+text+"</u></div></html>"; //color1
String str2 = "<html><div color='#c0c0c0'><u>"+text+"</u></div></html>"; //color2

JLabel jl = new JLabel(str1);
jl.addMouseListener(this);
jp.add(jl);


@Override
public void mouseEntered(MouseEvent e) {
  JLabel jl = (JLabel) e.getSource();
  currentString = jl.getText();
  jl.setText(str2); // this will change the text to color 2
}

@Override
public void mouseExited(MouseEvent e) {
  JLabel jl = (JLabel) e.getSource();
  jl.setText(str1); // Return to original color
}

Upvotes: 1

Related Questions