我遇到了一个问题而且我在编程方面很陌生我有Hero这个对象,我想在我的游戏课中使用他所有的方法这是我迄今为止编程的:
MainGame类:
class MainGame extends JComponent implements ActionListener, KeyListener{
Image Background;
MainGame() throws IOException {
Background = ImageIO.read(getClass().getResource("Background.png"));
}
public static void main (String[] args) throws IOException {
JFrame window = new JFrame("Adventure Times");
MainGame game = new MainGame();
window.add(game);
window.pack();
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
window.setVisible(true);
window.addKeyListener(game);
}
public void paintComponent(Graphics g) {
g.drawImage(Background, 0, 0, null);
}
public Dimension getPreferredSize() { return new Dimension(800, 600);
}
public void actionPerformed(ActionEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_RIGHT);
Hero.moveRight();
}
public void keyReleased(KeyEvent e) {
}
}
英雄级别:
public class Hero {
public int HeroX = 0;
public int HeroY = 0;
public int HeroSpeed = 0;
private BufferedImage Hero;
public Hero() {
try {
Hero = ImageIO.read(getClass().getResource("Hero.png"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
public void Draw(Graphics g) {
g.drawImage(Hero, HeroX, HeroY, null);
}
public void moveRight() {
HeroX += HeroSpeed;
}
public void moveLeft() {
HeroX -= HeroSpeed;
}
}
答案 0 :(得分:1)
To use Hero
's methods in your MainGame
class, you either need an instance of Hero
that can call them, or the method definitions have to include the static
keyword. In this application, static
doesn't work, and would in fact completely break your Hero
class if applied to the methods you have now, so you need to instantiate a Hero
. To do this, you need to, within MainGame
have the line
Hero achilles = new Hero();
With the code you currently have, however, this will throw an exception in the Hero
constructor that your try
statement doesn't catch, as it won't be an IOException
. The exception will be a result of trying to assign a value to a data type in
Hero = ImageIO.read(getClass().getResource("Hero.png"));
In fact, the code as it is won't even compile because of the attempted definition of Hero
as a member of type BufferedImage
. This is illegal, as you cannot use a class name as an identifier. This is similar to doing int = 4
, which makes no sense. Rename the BufferedImage
wherever it's referred to and the code should compile. For instance:
private BufferedImage sprite;
Alternatively, you could name it hero
with a lowercase 'h' to avoid the name collision. This is also in line with naming conventions and general best practice for Java, as well as most languages. Class names are usually capitalized, while member names are usually lowercase. For more info on naming conventions, see here.