Using image in place of Rectangle in Java? -
it's first time trying create 2d game in java , made little 8-bit character want set in place of rectangle appears on screen. can't quite understand how .png image rectangle's place, or how go making character, in case, image saved hard drive. thanks!
import javax.swing.*; import java.awt.*; import java.awt.event.keyadapter; import java.awt.event.keyevent; public class keying extends jpanel { public rectangle character; public int charw = 24; public int charh = 36; public boolean right = false; public boolean left = false; public boolean = false; public boolean downwards = false; public keying(display f, images i) { character = new rectangle(180, 180, charw, charh); f.addkeylistener(new keyadapter() { public void keypressed(keyevent e) { if (e.getkeycode() == keyevent.vk_d) { right = true; } if (e.getkeycode() == keyevent.vk_a) { left = true; } if (e.getkeycode() == keyevent.vk_s) { downwards = true; } if (e.getkeycode() == keyevent.vk_w) { = true; } } public void keyreleased(keyevent e) { if (e.getkeycode() == keyevent.vk_d) { right = false; } if (e.getkeycode() == keyevent.vk_a) { left = false; } if (e.getkeycode() == keyevent.vk_s) { downwards = false; } if (e.getkeycode() == keyevent.vk_w) { = false; } } }); } public void paintcomponent(graphics g) { super.paintcomponent(g); this.setbackground(color.white); g.setcolor(color.black); g.fillrect(character.x, character.y, character.width, character.height); if (right) { character.x += 1; } if (left) { character.x -= 1; } if (down) { character.y += 1; } if (up) { character.y -= 1; } repaint(); } }
the process relatively simple...
start loading character image...
public class keying extends jpanel { //public rectangle character; private java.awt.bufferedimage character; private java.awt.point characterlocation; //... public keying(display f, images i) throws ioexception { character = javax.imageio.read(...); characterlocation = new point(0, 0); //...
see reading/loading image more details...
then, want paint character
image...
@override protected void paintcomponent(graphics g) { g.drawimage(character, characterlocaiton.x, characterlocation.y, this);
advice
avoidkeylistener
, it's prone focus issues don't want deal with. instead utilize key bindings, see how utilize key bindings more details avoid putting logic within of paint routines, painting can occur @ time, many of don't control, have character moving in directions don't expect or faster should. instead, belongs within main game loop responsible updating state , scheduling paint requests. never alter state of component within paint method, cause infinite loop of paint requests, consume systems resources. within context, don't phone call setbackground
(by time phone call this, background has been painted anyway) or repaint
java
No comments:
Post a Comment