问题:
当使用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);
}
}
运行结果:

在使用Swing开发时,遇到JFrame添加Label组件显示乱码的问题。原因在于源码中使用了AWT的Label而非Swing的JLabel。修正方法是将Label改为JLabel,确保在Swing环境中正确使用组件。修改后的代码成功显示了文字,解决了乱码问题。

被折叠的 条评论
为什么被折叠?



