java - How to move a Rectangle with arrow keys? -
i have frame rectangle in it. want know how can move rectangle in if clicked arrow keys. searched, , find few examples nothing worked (weird, should simple thing do)
here rectangle class:
public class playerone implements keylistener { int x,y; public playerone(jpanel panel){ this.x = panel.getwidth()/2; this.y = panel.getheight()/2; } public void paint(graphics g){ g.setcolor(color.red); g.fillrect(125, 480, 60, 10); } @override public void keypressed(keyevent arg0) { // todo auto-generated method stub int keycode = arg0.getkeycode(); if(keycode == arg0.vk_kp_right){ this.x+=5; } } @override public void keyreleased(keyevent arg0) { // todo auto-generated method stub } @override public void keytyped(keyevent arg0) { // todo auto-generated method stub } } this main:
public class pingpong extends jpanel { private static final long serialversionuid = -4170574729049260633l; //initialize table table = new table(); playerone po = new playerone(this); public void paintcomponent(graphics g){ super.paintcomponent(g); table.paint(g); po.repaint(g); } public static void main(string[] args){ jframe frame = new jframe(); frame.settitle("pong"); frame.setsize(326, 533); frame.add(new pingpong()).setbackground(color.dark_gray); frame.getcontentpane().setbackground(color.dark_gray); frame.setvisible(true); } }
there's bunch of problems here:
the problem rectangle drawing hardcoded, evidenced here:
public void paint(graphics g){ g.setcolor(color.red); g.fillrect(125, 480, 60, 10); } you need use x variable instead of 125
in order accept key press events, jpanel needs accept focus, can achieved following lines:
setfocusable(true); requestfocusinwindow(); you receive keyboard events , alter x value. unfortunately won't trigger repaint box still won't move.
you should break apart classes bit more allocation of responsibilities bit strange. when key event occurs, need tell jpanel repaint() updates reflected on screen.
Comments
Post a Comment