问题:
当使用Swing开发中的JFrame添加Label组件时在界面显示乱码:
源码:
package GUI.Swing;
import javax.swing.*;
import java.awt.*;
public class TestJFrame {
public static void main(String[] args) {
new TestJFrame().init();
}
//自定义初始化方法,贴近真实项目的游戏开发
public void init(){
JFrame testJFrame = new JFrame("测试JFrame");
testJFrame.setBounds(100,100,200,200);
testJFrame.setVisible(true);
//Swing必须在容器中设置颜色,否则不能生效
//testJFrame.getContentPane().setBackground(Color.red);
//JLabel label = new JLabel("this is 一段文字");
Label label = new Label("this is 一段文字");
testJFrame.add(label);
//点击X按钮触发关闭事件
testJFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
运行结果:
解决方法:
将Label改成JLabel即可,要注意的是,Swing开发略微不同于AWT开发。Label在AWT中使用。
源码:
package GUI.Swing;
import javax.swing.*;
public class TestJFrame {
public static void main(String[] args) {
new TestJFrame().init();
}
//自定义初始化方法,贴近真实项目的游戏开发
public void init(){
JFrame testJFrame = new JFrame("测试JFrame");
testJFrame.setBounds(100,100,200,200);
testJFrame.setVisible(true);
//Swing必须在容器中设置颜色,否则不能生效
//testJFrame.getContentPane().setBackground(Color.red);
JLabel label = new JLabel("this is 一段文字");
testJFrame.add(label);
//点击X按钮触发关闭事件
testJFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
}
运行结果: