Java Swing开发 Label标签 界面中文出现乱码解决方案

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

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

运行结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值