2 回答
TA贡献2011条经验 获得超2个赞
img您每次调用时都在设置变量值repaint(),这会导致闪烁。而是在你的构造函数中初始化它一次。在这种情况下也不需要额外的 make 方法。这应该有效:
import java.awt.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import java.awt.event.*;
class MyFrame extends Frame implements KeyListener {
BufferedImage img;
int x = 100, y = 100;
public MyFrame() {
super("Box");
this.setSize(480, 480);
this.setVisible(true);
this.addKeyListener(this);
this.requestFocus();
this.setResizable(false);
try {
img = ImageIO.read(new File("c:/users/udesh_2/desktop/Boundary.jpg"));
} catch (IOException io) {
io.printStackTrace();
}
}
@Override
public void paint(Graphics g) {
super.paint(g);
g.drawImage(img, 0, 0, getWidth(), getHeight(), this);
g.setColor(Color.black);
g.fillOval(x, y, 40, 40);
}
public static void main(String $[]) {
MyFrame f = new MyFrame();
f.repaint();
}
public void keyPressed(KeyEvent key) {
boolean found = false;
if (key.getKeyCode() == KeyEvent.VK_UP) {
found = true;
y--;
}
if (key.getKeyCode() == KeyEvent.VK_DOWN) {
found = true;
y++;
}
if (key.getKeyCode() == KeyEvent.VK_LEFT) {
found = true;
x--;
}
if (key.getKeyCode() == KeyEvent.VK_RIGHT) {
found = true;
x++;
}
if (found) {
repaint();
}
}
public void keyTyped(KeyEvent key) {
}
public void keyReleased(KeyEvent key) {
}
}
TA贡献1848条经验 获得超10个赞
import java.awt.*;
import java.io.*;
import java.awt.image.*;
import javax.imageio.ImageIO;
import java.awt.event.*;
class MyFrame extends Frame implements KeyListener {
BufferedImage img;
Image _img;
Graphics gfx;
int x = 100, y = 100;
public MyFrame() {
super("Box");
this.setSize(1000,780);
this.setVisible(true);
this.addKeyListener(this);
this.requestFocus();
this.setResizable(false);
try {
img = ImageIO.read(new File("c:/users/udesh_2/desktop/Boundary.jpg"));
} catch (IOException io) {
io.printStackTrace();
}
_img=createImage(getWidth(),getHeight());
gfx=_img.getGraphics();
}
@Override
public void paint(Graphics g) {
if(img!=null){
gfx.drawImage((Image)img,0,0,getWidth(),getHeight(),this);
gfx.fillOval(x,y,30,30);
g.drawImage(_img, 0, 0, getWidth(), getHeight(), this);
try
{
Thread.sleep(70);
}catch(Exception e){System.out.println(e);}
}
}
public static void main(String $[]) {
MyFrame f = new MyFrame();
f.repaint();
}
public void keyPressed(KeyEvent key) {
boolean found = false;
if (key.getKeyCode() == KeyEvent.VK_UP) {
found = true;
y-=2;
}
if (key.getKeyCode() == KeyEvent.VK_DOWN) {
found = true;
y+=2;
}
if (key.getKeyCode() == KeyEvent.VK_LEFT) {
found = true;
x-=2;
}
if (key.getKeyCode() == KeyEvent.VK_RIGHT) {
found = true;
x+=2;
}
if (found) {
repaint();
}
}
public void keyTyped(KeyEvent key) {
}
public void keyReleased(KeyEvent key) {
}
}
添加回答
举报