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

JavaSE-12 Eclipse环境下Graphics2D无法解析类型问题求助

解决JavaSE-12中Graphics2D无法解析的问题

问题详情

我是Java新手,跟着YouTube教程开发游戏,使用Eclipse IDE(JavaSE-12)。已经导入java.awt.Graphics2D,编辑时错误消失,但运行程序后又出现两个错误:

  • Graphics2D cannot be resolved to a type
  • The import java.awt.Graphics2D cannot be resolved

其他如Graphics、Dimension、JPanel等类均可正常导入使用。已尝试删除module-info.java但无效,相关代码、模块信息及类型过滤器设置如下:

代码示例

package main;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;

import javax.swing.JPanel;

public class GamePanel extends JPanel implements Runnable{
    
    // 屏幕设置
    final int originalTileSize = 16;
    final int scale = 3; // 最终 tile 大小为48x48

    final int tileSize = originalTileSize * scale;
    final int maxScreenCol = 16;
    final int maxScreenRow = 12;
    final int screenWidth = tileSize * maxScreenCol;
    final int screenHeight = tileSize * maxScreenRow;
    
    Thread gameThread;
    
    public GamePanel() {
        this.setPreferredSize(new Dimension(screenWidth, screenHeight));
        this.setBackground(Color.pink);
        this.setDoubleBuffered(true);
    }

    public void startGameThread() {
        gameThread = new Thread(this);
        gameThread.start();
    }
    
    @Override
    public void run() {
        while(gameThread != null) {
            update();
            repaint();
        }
    }
    
    public void update() {
    }
    
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g; // <--- 此处报错
        
        // (等问题解决后我打算绘制一个矩形)
        //g2.setColor(Color.white);
        //g2.fillRect(100, 100, tileSize, tileSize);
        //g2.dispose();
    }
}

当前配置

已勾选的类型过滤器

  • com.sun*
  • io.micrometer.shaded*
  • jdk.*
  • sun.*
  • java.awt.List

module-info.java内容

module Maistas {
   exports main;
   requires transitive java.desktop;
}

项目结构

项目结构


解决步骤

1. 修正类型过滤器设置

你当前勾选的java.awt.List是单个类的过滤器,这会导致Eclipse仅允许访问java.awt.List,而屏蔽了java.awt.Graphics2D等其他同包类。

操作:

  • 打开Eclipse偏好设置:Window > Preferences > Java > Appearance > Type Filters
  • 找到并移除java.awt.List这个过滤器
  • 无需添加其他java.awt相关过滤器,保持默认即可

2. 确认模块依赖正确性

你的module-info.java中requires transitive java.desktop;配置是正确的,因为java.awt.Graphics2D属于java.desktop模块。如果之前删除过该文件,重新创建并添加此依赖即可。

3. 清理重建项目

  • 右键项目,选择Clean...,清理项目构建缓存
  • 再次右键项目,选择Project > Build Project重新构建

4. 验证JDK版本配置

确保项目使用的是JavaSE-12:

  • 右键项目 > Properties > Java Build Path > Libraries,检查JRE System Library是否为JavaSE-12
  • 切换到Java Compiler选项卡,确认Compiler compliance level设置为12

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 10:36:59