简体   繁体   English

Java swing,带有html文本的JLabel在悬停时无法正确呈现

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

I've come across this wierd interaction with my JLabel and html. 我已经与我的JLabel和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. 如果我在jlabel构造函数的字符串中使用html并将鼠标悬停在JLabel上,则会弄乱我的整个JPanel,将所有内容放在一行上,并且不考虑对组件的任何限制。 But if I just use a simple string like "test", the hover effect works correctly. 但是,如果我只使用“ test”之类的简单字符串,则悬停效果可以正常工作。

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);
}

When you are passing HTML formatted text you can not change the formatting of that text using the standard java library. 当您传递HTML格式的文本时,您无法使用标准Java库更改该文本的格式。

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 一种可能的解决方法是根据需要创建具有不同格式的字符串,并使用SetText方法更改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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM