You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java在public static void中调用fillRect时g2D变量无法解析如何解决

问题修复方案

核心错误原因

  • 作用域问题:g2D是MyPanel类paint()方法内的局部变量,仅在该方法内部生效,外部类Con完全无法访问该变量
  • Swing绘图规范错误:所有绘图操作必须在重写的paintComponent()方法(Swing推荐替代旧的paint()方法)中执行,Graphics2D对象由Swing系统在触发重绘时自动传入,无法在普通方法/main方法中直接创建使用
  • 逻辑结构错误:控制台输入逻辑和Swing绘图逻辑分属不同线程,不能直接在输入处理代码中调用绘图API,需要先存储输入结果,再主动触发面板重绘,在重绘方法中根据存储的结果执行绘制

可运行的修改后代码

import javax.swing.*;
import java.awt.*;
import java.util.Scanner;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class TestDraw {
    // 存储输入的字符串,供绘图时使用
    public static String inputStr = "";

    public static void main(String[] args) {
        // 先处理控制台输入
        Scanner input = new Scanner(System.in);
        System.out.println("Enter your message: ");
        inputStr = input.nextLine();
        input.close();

        // 启动Swing窗口
        new MyFrame();
    }

    static class MyFrame extends JFrame{
        MyPanel panel;
        MyFrame(){
            panel = new MyPanel();
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.add(panel);
            this.pack();
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        }
    }

    static class MyPanel extends JPanel{
        Image image;

        MyPanel(){
            // 注意这里Bob.jpg要放在项目根目录,否则替换为绝对路径
            image = new ImageIcon("Bob.jpg").getImage();
            this.setPreferredSize(new Dimension(500,500));
        }

        // 重写paintComponent方法执行绘图,这是Swing标准绘图入口
        @Override
        protected void paintComponent(Graphics g) {
            // 必须先调用父类方法清屏
            super.paintComponent(g);
            Graphics2D g2D = (Graphics2D) g;

            // 原来的绘图逻辑
            g2D.drawImage(image, 1, 1, null);
            g2D.setPaint(Color.green);
            g2D.setPaint(Color.pink);
            g2D.fillRect(0, 0, 5, 5);
            g2D.setPaint(Color.red);

            int[] xPoints = {150,250,350};
            int[] yPoints = {300,150,300};
            g2D.setPaint(Color.yellow);
            g2D.fillPolygon(xPoints, yPoints, 3);

            // 新增:根据输入的字符串判断绘制
            char[] ch = inputStr.toCharArray();
            for (int i = 0; i < ch.length; i++) {
                if(ch[i] == 'a'){
                    // 这里调整坐标避免重叠,每遇到一个a就往后挪6个像素画矩形
                    g2D.fillRect(10 + i*6, 10,5,5);
                }
            }
        }
    }
}

修改说明

  • 去掉了无意义的泛型声明和冗余的Con类,把输入逻辑和绘图逻辑整合到统一的结构中
  • 新增静态变量inputStr存储控制台输入的内容,供绘图方法读取
  • 把绘图入口替换为Swing推荐的paintComponent()方法,第一行先调用super.paintComponent(g)清屏,避免绘图残留
  • 把判断字符a的逻辑移到paintComponent()内部,直接使用Swing传入的g2D对象执行绘制,每个匹配到的a会错开坐标绘制避免重叠
  • 内部类都加了static修饰,避免非静态内部类依赖外部类实例无法创建的问题
  • 主类main方法改为静态,保证程序可以正常启动

内容的提问来源于stack exchange,提问作者Coding Java

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 00:54:00