loops - Java drawimage in gameloop -
i'm trying learn program first game , understand correctly every step make. i'll face double buffering , other things later. i'm trying load image in game loop. have 2 classes. first it's jframe calling start method. wonder if there ugly code, in here (i think so). so, why images not showing up?
public class mypanel extends jpanel implements runnable{ //fields public static int width = 1024; public static int height = width / 16 * 9; private bufferedimage bg; private bufferedimage charac; private boolean running; private thread t1; private int startposx = width / 2; private int startposy = height / 2; private int cordx = startposx; private int cordy = startposy; int speed = 50; //methods public synchronized void start (){ running = true; t1 = new thread (this); t1.start(); } public synchronized void stop (){ running = false; try { t1.join(); system.out.println("the game stopped"); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } //init public mypanel(){ setpreferredsize(new dimension(width, height)); setfocusable(true); requestfocus(); addkeylistener(this); } //main run method public void run(){ while (running){ load(); system.out.println("the game runs"); repaint(); } } //paint graphics method public void paint (graphics g){ super.paint(g); g.drawimage(bg, 0, 0, this); g.drawimage(charac, 110, 280, this); } //load images in memory public void load (){ try { string path1 = "res/bg.png"; bg = imageio.read(new file (path1)); string path2 = "res/charac.png"; charac = imageio.read(new file (path2)); } catch (ioexception e) { e.printstacktrace(); } }
so, did testing paint vs paintcomponent , saw first draws on top of jpanel background. anyway, can't still see changing lines to
public void run(){ while (running){ load(); system.out.println("the game runs"); } } //paint graphics method public void paintcomponent (graphics g){ super.paint(g); g.drawimage(bg, 0, 0, null); g.drawimage(charac, 110, 280, null); } //load images method above
and yes, i've added panel frame, here other class
public class game {
public static void main (string [] args){ jframe frame = new jframe(); frame.setignorerepaint(true); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setcontentpane(new mypanel()); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); mypanel game = new mypanel(); game.start(); }
Comments
Post a Comment