在研究java.awt.Label和javax.swing.JLabel怎么换行时,发现JLabel竟然能用html !!!
演示1
package labelJLabel;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.Field;
import java.util.stream.Stream;
import javax.swing.*;
public class LabeJLabel换行 {
static Frame frame ;
static Label label001 , label002;
static JLabel jlabel001 , jlabel002;
static {
try {
frame = (Frame)Frame.class.getDeclaredConstructor(String.class).newInstance("LabeJLabel换行");
frame.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent event) {System.exit(0);}
});
frame.setLayout(new GridLayout(0, 1, 5, 5));
frame.setBounds(100, 50, 1600, 900);
}catch(Throwable th) {th.printStackTrace();}
label001=new Label("Label的换行用\\n\r\n换行没有用"); label001.setBackground(Color.red);
label002 = new Label("""
<html>
<h1 style="color:red">label不能用Html</h1>
<br/>
<b style="font-size:30px; color:blue" > 不能用<br/>换行 </b>
<svg>
<line x1="0" y1="0" x2="100%" y2="100%" stroke="black" strokewidth="10" />
</svg>
</html>
""");
label002.setBackground(Color.orange);
jlabel001 = new JLabel("JLabel用\\n\r\n换行没有用"); jlabel001.setBackground(Color.yellow); jlabel001.setOpaque(true);;
jlabel002 = new JLabel("""
<html>
<span style="color:red; font-size:30px;">JLabel竟然能用Html!!! 太帅了!</span> <br/>
<b style="font-size:30px; color:blue" > 用<br/>换行 </b>
<svg>
<line x1="0" y1="0" x2="100%" y2="100%" stroke="black" strokewidth="10" />
</svg>
<div style="position:fixed; left:300px; top:10px; width:500px; height:50px; font-size:20px; background:#0099ff; border:10px solid black; border-radius:50%;" >html功能不完整</style>
<script>alert()</script>
</html>
""");
jlabel002.setOpaque(true); jlabel002.setBackground(Color.green);
try {
Field fields[] = Class.forName(new Throwable().getStackTrace()[0].getClassName()).getDeclaredFields();
Stream.of(fields).forEach(field->{
try {
Component component = (Component)field.get(null);
if(frame!=component) {
frame.add(component);
}
} catch (Exception e) {e.printStackTrace(); }
});
}catch(Throwable th) {th.printStackTrace();}
frame.setVisible(true);
}
public static void main(String...arguments) {}
}