java - creating squares on event -


i trying create game same system snake. have created window jpanel on it, given background , drawn lines show user squares.

board 600x600 (601x601 visible). squares 20x20.

now trying add way put coloured squares onto board , detect if coloured square there ideally.

public class createwindow extends jframe {      jpanel gamearea;     static jlayeredpane java_window;     image background;      public void createwindow() {         dimension panel_size = new dimension(800, 800);         this.setsize(800,800);         this.setdefaultcloseoperation(jframe.exit_on_close);         this.setvisible( true );         this.settitle("linerage");         getcontentpane().setbackground(color.white);           java_window = new jlayeredpane();         this.add(java_window);         java_window.setpreferredsize(panel_size);          gamearea = new jpanel()         {             @override             public void paint(graphics g) {                 g.setcolor(color.black);                 g.fillrect(0,0,601,601);                  g.setcolor(color.gray);                 // cut map sections                 int x;                 //draw vertical lines                 for(x = 0; x < 31; x++) {                     g.drawline(x*20,0,x*20,600);                 }                     //draw horizontal lines                 for(x = 0; x < 31; x++) {                     g.drawline(0,x*20,600,x*20);                 }                  }              public void paintsquare (int x,int y) {                 //check if square painted                  //paint square                 rectangle rect = new rectangle(x, y, 20, 20);                 gamearea.add(rect);             }         };         java_window.add(gamearea, jlayeredpane.default_layer);         gamearea.setbounds(20, 20, 601, 601);         gamearea.setvisible(true);     } } 

so java_window (800x800) has white background, game_area (601x601) has black background 32 lines along , across divide squares.

public void paintsquare (int x, int y) {     //check if square painted      //paint square     rectangle square = new rectangle(x, y, 20, 20);     gamearea.add(square); } 

paintsquare called object (the main game) , check background of square, if free paint square on (20x20).

your exact question unclear here pointers:

  • use paintcomponent rather paint when doing custom painting in swing. don't forget call super.paintcomponent(g).
  • java.awt.rectangle not derived jcomponent (or component) can't added container.
  • one approach take use fillrect , "paint" squares:

also, in java, methods start lowercase letter. adding , previous point together, do:

public void paintsquare(graphics g, int x, int y) {    g.fillrect(x, y, 20, 20); } 

here, paintsquare method called paintcomponent.


Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -