Java 实际论证与形式论证
所以我,;我遵循一个教程,我完全遵循它,但当我测试时,它抛出一个错误Java 实际论证与形式论证,java,Java,所以我,;我遵循一个教程,我完全遵循它,但当我测试时,它抛出一个错误 Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - constructor Main in class spritesheet.Main cannot be applied to given types; required: java.awt.Color found: no arguments rea
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - constructor Main in class spritesheet.Main cannot be applied to given types;
required: java.awt.Color
found: no arguments
reason: actual and formal argument lists differ in length
at spritesheet.Main.main(Main.java:48)
Java Result: 1
错误
这是我的代码:
package spritesheet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
public class Main extends JFrame {
BufferedImage sprite;
private final Color Color;
public Main(Color white){
setSize(800, 600);
setVisible(true);
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setBackground(Color=white);
init();
}
private void init(){
BufferedImageLoader loader = new BufferedImageLoader();
BufferedImage spriteSheet = null;
try {
spriteSheet = loader.loadImage("spritesheet.png");
} catch (IOException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
SpriteSheet ss = new SpriteSheet(spriteSheet);
sprite = ss.grabSprite(0, 0, 16, 16);
}
@Override
public void paint(Graphics g){
g.drawImage(sprite, 100, 100, null);
repaint();
}
public static void main(String[] args) {
Main Main = new Main();
}
}
此代码旨在在白色背景上显示静态图像,但它会引发错误或显示透明背景。然后它就飞出去了,让我很恼火(
我做错了什么???你这样称呼你的班级
Main Main = new Main();
但是您需要向它传递一个参数,因为您将它定义为
public Main(Color white) { ... }
你可以把它改成
Main Main = new Main(Color.WHITE);
及
编辑
您现在可以做两件事。将颜色
变量设置为静态,如下所示:
private static Color Color;
或者将Main
构造函数更改为
public Main() {
setSize(800, 600);
setVisible(true);
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
Color = Color.WHITE;
setBackground(Color);
init();
}
通常,如果未定义任何自定义构造函数,编译器将添加一个不接受任何参数的默认构造函数
由于您有一个自定义构造函数
Main(白色)
(我建议您将参数命名为“Color”-可以指定任何颜色),这是Main
类中唯一的构造函数。因此,您必须通过提供Color对象作为参数来调用自定义构造函数。感谢您的帮助,但编译器会抛出此错误:在线程“Main”中运行:异常java.lang.RuntimeException:不可编译的源代码-无法从spritesheet.Main.Main(Main.java:49)的静态上下文中引用非静态变量颜色Java结果:1您收到的错误表明您的main
入口点是static
,并且只能使用static
变量。请使用color
static`或像上面我的编辑一样更改代码。
public Main() {
setSize(800, 600);
setVisible(true);
setResizable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
Color = Color.WHITE;
setBackground(Color);
init();
}