Label和Button在代码编码与系统编码不同时显示中文会乱码, JLabel和JButton则不会
测试代码:
package labelJLabel;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.stream.Stream;
import javax.swing.*;
public class Label和Button在代码编码与系统编码不同时中文会乱码 {
static Label label = new Label("Label在.java代码编码与系统编码不同时,显示中文会乱码");
static JLabel jlabel = new JLabel("JLabel在.java代码编码与系统编码不同时,显示中文不会乱码");
static Button button = new Button("Button在.java代码编码与系统编码不同时,显示中文会乱码");
static JButton jbutton = new JButton("JButton在.java代码编码与系统编码不同时,显示中文不会乱码");
public static void main(String...arguments) {
Frame frame = new Frame(Thread.currentThread().getStackTrace()[1].getClassName());
frame.addWindowListener(new WindowAdapter() {
@Override public void windowClosing(WindowEvent event) {System.exit(0);}
});
frame.setLayout(new GridLayout(0, 2, 5, 5)); frame.setBounds(100, 50, 1600, 900);
try {
throw new Exception("不要大惊小怪");
}catch(Throwable th) {th.printStackTrace();
try {
Field fields[] = Class.forName(th.getStackTrace()[0].getClassName()).getDeclaredFields();
Stream.of(fields).forEach(field->{
if(field.getModifiers()==Modifier.STATIC) {
try {
Component component = (Component)field.get(null);
component.setBackground(Color.CYAN);
component.setFont(new Font("", Font.BOLD, 25));
frame.add(component);
}catch(Exception ex) {}
}
});
}catch(Exception ex) {}
}
frame.setVisible(true);
}
}
看不到JLabel的背景色是因为JLabel默认的isOpaque()是false, setOpaque(true)后就能看到