Java Swing等轴视口程序编译错误求助(Eclipse环境)
Java Swing等轴视口程序编译错误解决
问题详情
我是学Java第5周的新手,第一次用Java Swing写程序,在Eclipse里写了个等轴视口程序,代码如下:
package main; import javax.swing.*; import java.awt.*; public class IsometricViewport extends JPanel { private static final int TILE_WIDTH = 64; private static final int TILE_HEIGHT = 32; public IsometricViewport() { setPreferredSize(new Dimension(480, 640)); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); // Draw isometric tiles for (int x = 0; x < getWidth(); x += TILE_WIDTH) { for (int y = 0; y < getHeight(); y += TILE_HEIGHT) { drawIsometricTile(g, x, y); } } // TODO: Draw characters and other game elements } private void drawIsometricTile(Graphics g, int x, int y) { int isoX = (x - y) / 2; int isoY = (x + y) / 2; g.setColor(Color.LIGHT_GRAY); g.fillRect(isoX, isoY, TILE_WIDTH, TILE_HEIGHT); g.setColor(Color.BLACK); g.drawRect(isoX, isoY, TILE_WIDTH, TILE_HEIGHT); } public static void main(String[] args) { SwingUtilities.invokeLater(() -> { JFrame frame = new JFrame("Isometric Viewport"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new IsometricViewport()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); }); } }
运行时控制台报错:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at main.IsometricViewport.main(viewport.java:39)
错误原因与解决步骤
这个错误是源文件名和类名不匹配导致的:
- Java要求public类的文件名必须和类名完全一致(大小写敏感),你的主类是
IsometricViewport,但错误里显示文件名叫viewport.java,两者不匹配,Eclipse无法正常编译。
解决方法:
- 在Eclipse项目里找到这个源文件
- 右键选「重命名」,把文件名改成
IsometricViewport.java - 重新编译运行即可
额外优化提示
你的等轴瓦片绘制逻辑有问题,当前代码会导致瓦片重叠错位,给你调整成正确的等轴网格绘制方式:
@Override protected void paintComponent(Graphics g) { super.paintComponent(g); // 定义网格行列数 int gridCols = 8; int gridRows = 12; // 计算网格中心偏移量,让瓦片居中显示 int offsetX = getWidth() / 2 - (TILE_WIDTH / 2); int offsetY = 50; // 遍历网格行列绘制瓦片 for (int col = 0; col < gridCols; col++) { for (int row = 0; row < gridRows; row++) { // 从网格坐标转换为屏幕坐标 int screenX = (col - row) * (TILE_WIDTH / 2) + offsetX; int screenY = (col + row) * (TILE_HEIGHT / 2) + offsetY; drawIsometricTile(g, screenX, screenY); } } } private void drawIsometricTile(Graphics g, int x, int y) { // 绘制等轴菱形(用多边形代替矩形) int[] xPoints = {x + TILE_WIDTH/2, x + TILE_WIDTH, x + TILE_WIDTH/2, x}; int[] yPoints = {y, y + TILE_HEIGHT/2, y + TILE_HEIGHT, y + TILE_HEIGHT/2}; g.setColor(Color.LIGHT_GRAY); g.fillPolygon(xPoints, yPoints, 4); g.setColor(Color.BLACK); g.drawPolygon(xPoints, yPoints, 4); }
这样就能画出正确的等轴网格了。
内容的提问来源于stack exchange,提问作者Igetmadefunof-onthisapp
相关产品推荐
相关产品推荐

