Java problem cant find image file
I am a student working on a homework project. I spent DAYS trying to get the following code to display an image on my new windows 7 laptop. I compiled it and ran it on my old xp pc and it worked! I really want to use my laptop. Any suggestions on how to get it to display the image? The java code. HTML and immage are all in the same sub directory on my flash drive. I tried moving them to the c:Program Files 开发者_JAVA百科(x86)\Java\jdk1.5.0_02\bin directory but it still didn't work.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.awt.image.*;
public class MoveIt extends Applet implements ActionListener
{
// set variables and componets
private Image cup;
Panel keypad = new Panel();
public int top = 15;
public int left = 15;
private Button keysArray[];
public void init()
{
cup = getImage(getDocumentBase(), "cup.gif");
Canvas myCanvas = new Canvas();
keysArray = new Button[5];
setLayout(new BorderLayout(5,5));
setBackground(Color.blue);
// set up keypad layout
keypad.setLayout(new BorderLayout(0,0));
keysArray[0] = new Button("Up");
keysArray[1] = new Button("Left");
keysArray[2] = new Button("Center");
keysArray[3] = new Button("Right");
keysArray[4] = new Button("Down");
// add buttons to the keypad panel
keypad.add(keysArray[0], BorderLayout.NORTH);
keysArray[0].addActionListener(this);
keypad.add(keysArray[1], BorderLayout.EAST);
keysArray[1].addActionListener(this);
keypad.add(keysArray[2], BorderLayout.CENTER);
keysArray[2].addActionListener(this);
keypad.add(keysArray[3], BorderLayout.WEST);
keysArray[3].addActionListener(this);
keypad.add(keysArray[4], BorderLayout.SOUTH);
keysArray[4].addActionListener(this);
// add canvas and keypad to the BorderLayout
add(myCanvas, BorderLayout.NORTH);
add(keypad, BorderLayout.SOUTH);
}
public void paint(Graphics g)
{
g.drawImage( cup, left, top, this );
}
public void actionPerformed(ActionEvent e)
{
// test for menu item clicks
String arg = e.getActionCommand();
if (arg == "Up")
top -=15;
else
if (arg == "Down")
top +=15;
else
if (arg == "Left")
left -=15;
else
if (arg == "Right")
left +=15;
else
{
top = 60;
left =125;
}
repaint();
}
}
I'm not the Applet
guy, but putting cup.gif
alongside MoveIt.html
and MoveIt.class
seemed to work. Also, you're overriding the paint()
method of Applet
, not that of Canvas
. As an aside, arg == "Up"
happens to work because Java strings are interned, but "Up".equals(arg)
is the more reliable predicate.
精彩评论