Checkers game GUI

I need help.
I know the basics of GUI programming.. i plan to use JBuilder's drag-and-drop development to create a checkers game for a software engineering class that i am taking at ASU. I have not played around with swing for about a year; i need help starting. How would i create a checkers layout? would i use a background image of a checkers board, or use some sort of grid layout?
any help to start creating a board game like a simple checkers game with JAVA would be helpful.
thankyou.
christian

This'll get you started;-
import java.applet.*;
import java.awt.*;
public class Gridder extends Applet{
   public void init(){}
   public void paint(Graphics g){
      super.paint(g);
      int x = getWidth()/8;
      int y = getHeight()/8;
      int Xx=0, Yy=0;
         for(int ii=0; ii<8; ii++){
            for(int jj=0; jj<8; jj++){
               if((ii+jj) % 2 ==0) g.setColor(Color.gray);
               else g.setColor(Color.lightGray);
               g.fillRect(Xx,Yy,x,y);
               Xx+=x;
         Xx=0;
         Yy+=y;
      Xx=0;
      Yy=0;
      g.setColor(Color.white);
         for(int ii=0; ii<9; ii++){
            g.drawLine(Xx,0,Xx,getHeight());
            g.drawLine(0,Yy,getWidth(),Yy);
            Xx +=x;
            Yy +=y;
}

Similar Messages

  • J2ME game gui? J2ME Canvas? J2ME polish? Which is better?

    I am currently trying to build a J2ME brochure like project which is required to have rich presentation.
    JAVA is not a problem for me as I've used it for quite a long time. But since I am very new in J2ME, I am confused which technology to use, should I use j2me game gui, j2me canvas or j2me polish?
    Using j2me game gui looks good. J2me canvas looks a bit tedious to me because for a brochure like project, it will mean I will probably end up using a lot of canvas which make the application quite big. Regarding to J2ME polish, there is not many materials or examples about it. it seems that J2ME polish hasn't been used a lot and I don't know whether it's good or not.
    Anybody knows something about those three? Please give me a hand.
    Thanks.

    J2ME Polish have licensing costs associated with it:
    http://www.j2mepolish.org/licenses.html
    As for Canvas VS GameCanvas:
    GameCanvas is MIDP 2.0 and up, so depending which devices your app supports you might want to stick with Canvas. GameCanvas eases graphics flushing, but double buffering can be implemented on Canvas like so:
    Image offscreen = isDoubleBuffered () ? null :
               Image.createImage (getWidth (), getHeight ());See http://www.developer.com/java/j2me/article.php/10934_1561591_8
    section: Avoiding Flickering

  • Problems with network Checkers Game

    HI all. I have a checkers game. But i can't create a network.
    Here is my work :
    Server:
    http://www.filefactory.com/file/agg5a77/n/Checkers_java
    Client:
    http://www.filefactory.com/file/agg5a78/n/client_java
    Can anybody help? =)

    I'm sorry for spam. Didn't think that was spam.
    Here server's part:
    public class Checkers extends JPanel {
       public static void main(String[] args) {
           ServerSocket s = new ServerSocket(1989);
           while(true)
           { Socket ss=s.accept();
             ObjectInputStream in = new ObjectInputStream(ss.getInputStream());
             ObjectOutputStream out = new ObjectOutputStream(raul.getOutputStream());
            JFrame window = new JFrame("Checkers");
            Checkers content = new Checkers();
            window.setContentPane(content);
            window.setSize(500,500);
            window.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
            window.setResizable(false); 
            window.setVisible(true);
       }------------------------------------------------------- Here are nested class CheckersMove.
    private static class CheckersMove {
          int fromRow, fromCol; 
          int toRow, toCol;    
          CheckersMove(int r1, int c1, int r2, int c2) {
             fromRow = r1;
             fromCol = c1;
             toRow = r2;
             toCol = c2;
    private static class CheckersData {
    void makeMove(CheckersMove move) {
             makeMove(move.fromRow, move.fromCol, move.toRow, move.toCol);
           * Make the move from (fromRow,fromCol) to (toRow,toCol).  It is
           * assumed that this move is legal.  If the move is a jump, the
           * jumped piece is removed from the board.  If a piece moves
           * the last row on the opponent's side of the board, the
           * piece becomes a king.
          void makeMove(int fromRow, int fromCol, int toRow, int toCol) {
             board[toRow][toCol] = board[fromRow][fromCol];
             board[fromRow][fromCol] = EMPTY;
             if (fromRow - toRow == 2 || fromRow - toRow == -2) {
                // The move is a jump.  Remove the jumped piece from the board.
                int jumpRow = (fromRow + toRow) / 2;  // Row of the jumped piece.
                int jumpCol = (fromCol + toCol) / 2;  // Column of the jumped piece.
                board[jumpRow][jumpCol] = EMPTY;
             if (toRow == 0 && board[toRow][toCol] == RED)
                board[toRow][toCol] = RED_KING;
             if (toRow == 7 && board[toRow][toCol] == BLACK)
                board[toRow][toCol] = BLACK_KING;
           * Return an array containing all the legal CheckersMoves
           * for the specfied player on the current board.  If the player
           * has no legal moves, null is returned. 
          CheckersMove[] getLegalMoves(int player) {
             if (player != RED && player != BLACK)
                return null;
             int playerKing;  // The constant representing a King belonging to player.
             if (player == RED)
                playerKing = RED_KING;
             else
                playerKing = BLACK_KING;
             ArrayList<CheckersMove> moves = new ArrayList<CheckersMove>();  // Moves will be stored in this list.
             /*  First, check for any possible jumps. 
             for (int row = 0; row < 8; row++) {
                for (int col = 0; col < 8; col++) {
                   if (board[row][col] == player || board[row][col] == playerKing) {
                      if (canJump(player, row, col, row+1, col+1, row+2, col+2))
                         moves.add(new CheckersMove(row, col, row+2, col+2));
                      if (canJump(player, row, col, row-1, col+1, row-2, col+2))
                         moves.add(new CheckersMove(row, col, row-2, col+2));
                      if (canJump(player, row, col, row+1, col-1, row+2, col-2))
                         moves.add(new CheckersMove(row, col, row+2, col-2));
                      if (canJump(player, row, col, row-1, col-1, row-2, col-2))
                         moves.add(new CheckersMove(row, col, row-2, col-2));
             /*  If any jump moves were found, then the user must jump, so we don't
              add any regular moves.  However, if no jumps were found, check for
              any legal regualar moves.
             if (moves.size() == 0) {
                for (int row = 0; row < 8; row++) {
                   for (int col = 0; col < 8; col++) {
                      if (board[row][col] == player || board[row][col] == playerKing) {
                         if (canMove(player,row,col,row+1,col+1))
                            moves.add(new CheckersMove(row,col,row+1,col+1));
                         if (canMove(player,row,col,row-1,col+1))
                            moves.add(new CheckersMove(row,col,row-1,col+1));
                         if (canMove(player,row,col,row+1,col-1))
                            moves.add(new CheckersMove(row,col,row+1,col-1));
                         if (canMove(player,row,col,row-1,col-1))
                            moves.add(new CheckersMove(row,col,row-1,col-1));
             /* If no legal moves have been found, return null.  Otherwise, create
              an array just big enough to hold all the legal moves, copy the
              legal moves from the ArrayList into the array, and return the array. */
             if (moves.size() == 0)
                return null;
             else {
                CheckersMove[] moveArray = new CheckersMove[moves.size()];
                for (int i = 0; i < moves.size(); i++)
                   moveArray[i] = moves.get(i);
                return moveArray;
          }  // end getLegalMoves
           * Return a list of the legal jumps that the specified player can
           * make starting from the specified row and column.
          CheckersMove[] getLegalJumpsFrom(int player, int row, int col) {
             if (player != RED && player != BLACK)
                return null;
             int playerKing;  // The constant representing a King belonging to player.
             if (player == RED)
                playerKing = RED_KING;
             else
                playerKing = BLACK_KING;
             ArrayList<CheckersMove> moves = new ArrayList<CheckersMove>();  // The legal jumps will be stored in this list.
             if (board[row][col] == player || board[row][col] == playerKing) {
                if (canJump(player, row, col, row+1, col+1, row+2, col+2))
                   moves.add(new CheckersMove(row, col, row+2, col+2));
                if (canJump(player, row, col, row-1, col+1, row-2, col+2))
                   moves.add(new CheckersMove(row, col, row-2, col+2));
                if (canJump(player, row, col, row+1, col-1, row+2, col-2))
                   moves.add(new CheckersMove(row, col, row+2, col-2));
                if (canJump(player, row, col, row-1, col-1, row-2, col-2))
                   moves.add(new CheckersMove(row, col, row-2, col-2));
             if (moves.size() == 0)
                return null;
             else {
                CheckersMove[] moveArray = new CheckersMove[moves.size()];
                for (int i = 0; i < moves.size(); i++)
                   moveArray[i] = moves.get(i);
                return moveArray;
          }  // end getLegalMovesFrom()Edited by: Java-Maker on May 10, 2009 9:10 AM

  • Tables and Rounding Errors on Board Game Gui

    Hello,
    So I am in a software development class , and my team and I are developing a software version of a board game that uses numbered tiles placed on a board in a somewhat scrabble-esque way.
    Here is a picture of the game board:
    [http://img90.imageshack.us/img90/1052/untitledqv3.png|http://img90.imageshack.us/img90/1052/untitledqv3.png]
    Currently, a problem that we are working on is that as the tiles get further and further away from the center of the board, they are displayed further and further askew from the board lines. I have another picture to demonstrate what I'm talking about more clearly.
    [http://img225.imageshack.us/img225/4605/untitled2nn0.png|http://img225.imageshack.us/img225/4605/untitled2nn0.png]
    As the tiles get further away from the center, they are displayed more askew.
    We think that this happens because we are using a gridbag layout to add tile objects to, which displays the tiles in a certain spacing and orientation, and then we draw the board ourselves. When we draw the board, we get rounding errors inherent in the use of ints, and the lines become a bit off, with the problem getting worse as it gets further and further away from the center.
    Here is the code that we use to initialize the layout and add the tiles to it:
         //set the layout
    setLayout(new GridLayout(7, 7, 7, 7));
    //initialize the array with the references to all the tiles that we are going to add
    //to the layout
    squares = new SquareView[7][7];
    for (int i = 0; i < 7; i++) {
         for (int j = 0; j < 7; j++) {
              //create the tile, put a reference to it in the array
              squares[i][j] = new SquareView(boardModel.getSquare(new Point(j, i)), listener, handler);
              //add the tile to the layout
              add(squares[i][j]);
    }And here is the code that we are using to draw the lines for the board:
    GridLayout layout = (GridLayout) getLayout();
    //getting the dimensions of the board
    int rows = layout.getRows();
    int columns = layout.getColumns();
    int width = (getWidth() / columns);
    int height = (getHeight() / rows);
    g2.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), null);
    for (int i = 0; i < 8; i++) {
         // Vertical lines
         g2.drawLine(i * width, 0, i * width, rows * height);
         // Horizontal lines
         g2.drawLine(0, i * height, columns * width, i * height);
    }I think that our problems come from the innacuracy of ints, but if there is some addition or subtraction trick that we could pull, then let me know.
    Also, I was sort of looking into tables, and I was wondering if maybe we could use tables to do this, and have Java do our resizing for us.

    j.law wrote:
    We think that this happens because we are using a gridbag layout to add tile objects to, From the snippets of code, it's looking as though you're using GridLayout. But that's OK as GridLayout should work fine here.
    GridLayout layout = (GridLayout) getLayout();
    //getting the dimensions of the board
    int rows = layout.getRows();
    int columns = layout.getColumns();
    int width = (getWidth() / columns);
    int height = (getHeight() / rows);
    g2.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), null);
    for (int i = 0; i < 8; i++) {
         // Vertical lines
         g2.drawLine(i * width, 0, i * width, rows * height);
         // Horizontal lines
         g2.drawLine(0, i * height, columns * width, i * height);
    }I have no idea of this will improve things, but what about:
    GridLayout layout = (GridLayout) getLayout();
    int rows = layout.getRows();
    int columns = layout.getColumns();
    double width = (getWidth() / columns); //** how about using doubles here
    double height = (getHeight() / rows);  //** how about using doubles here
    g2.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), null);
    for (int i = 0; i < 8; i++) {
         // Vertical lines
         g2.drawLine(i * width, 0, (int)(i * width), (int)(rows * height)); // and casting?
         // Horizontal lines
         g2.drawLine(0, (int)(i * height), (int)(columns * width), (int)(i * height));
    }

  • Checkers game switch between black and white

    Hey,
    I want to put in a button so when you puch the button the other player can be activated and the last player is turned non-active.
    I thougth I could do this in the controller, I'm working with mvc, so when the button is pressed an int is raised by one and in the
    mouselistener I can use this int to say if he may pick a black or white checker. But I don't know how to get this int, that I have put
    in the actionPerformed, out of the void actionPerformed and in to the void mouseClicked.
    greets

    Or is there an other easier way to switch between my two different checkers???
    greets

  • [HELP] Checkers (Droughts) game.

    I hope everyone is fine,
    I want to make a checkers game by java that allows two players to play against each other.
    But I am beginner in programing.
    So if anybody could post some codes for the game or even some outlines , I would be thankful.

    Khalid.S wrote:
    I want to make a checkers game by java that allows two players to play against each other.
    But I am beginner in programing.Then I'd suggest starting with something simpler. Mastermind perhaps?
    Checkers has a lot of components to it - board, pieces, allowable moves, piece taking and conversion - that make it a big project to take on board at this stage.
    Winston

  • How do i host my 2 player checker game

    Ok so im currently taking a java course at my university and my project is to create a 2 player game of checkers, to be played online.
    I have an applet "Checkers.java" and application "CheckerServer.java"
    The CheckerServers waits for 2 players (i must first run the application, and then run the applet twice)
    The game is complete and it runs great, the applet uses "127.0.0.1" as the server for local testing
    now my question is how to i put this on my website which is hosted via GoDaddy
    I know how to host an applet, a simple html file with the <APPLET CODE"whatever.class" ARCHIVE="whatever.jar">
    but how do i make it so that the server application is running before the applet loads?
    and how do i make it so that when 2 different people visit the website with the applet they both use the same CheckerServer application?
    if anyone can point me in the direction, what to research, is this an html problem or must it be somehow included in my code.
    Anything helps, if needed i can upload my code here, but is rather long. the applet is a combination of 5 classes and then theres the server app
    Edited by: 806417 on Oct 29, 2010 4:14 PM

    806417 wrote:
    but how do i make it so that the server application is running before the applet loads?Typically a server runs 24x7, or 8:00-5:00 M-F, or something . So you put your server app on your GD host, start it up, and let it run forever.
    and how do i make it so that when 2 different people visit the website with the applet they both use the same CheckerServer application?How is the applet connecting with the application now? I would assume it connects to some IP address and port. So both clients need to connect to the same port on the same server--the one that served them in the first place. I don't really understand what problem you're having here.
    Anything helps, if needed i can upload my code here, but is rather long. the applet is a combination of 5 classes and then theres the server appIf it comes to that, you most certainly will not upload your app. Not if you want anybody to read it anyway. If your question is about applet/server connectivity, you would write a tiny [url http://sscce.org]SSCCE that just has enough pieces to have an applet and a server trying to talk. No GUI stuff, no checkers game logic. None of that fluff.

  • Java Card Game (Carioca)

    Hi everyone.
    Im currently making a card game in java for a south american game called Carioca
    originally i had
    CariocaController, which controlled game logic such as creating cards and players, dealing the cards setting the cards etc.
    btnStartGame in GUI would run controller method startGame which would initialize everything then set the GUI.
    CariocaTablelGUI, which extended JFrame and set the game GUI by using swingcomponents (JButtons with ImageIcons for cards)
    Card, like it says, card suit, no and value
    Deck, which created an ArrayList<Card> + 2 jokers.
    Pile which extended ArrayList<Card>. (Used for creating the 2deck game, player hands, putdown pile)
    Ive never been to good with GUI's and not enjoying my inopropriate gui structure i decided to read about java game designs.
    I read OReilly Killer Game Programming in Java chapters 1-13 before it got into 3d java. and not feeling it provided the examples i needed i went back to my old book
    Deitel & Deitel How to program Java Fifth edition. which has a case study of ElevatorSimulation which uses the Model View Controller design pattern.
    I have used this simulation as my guide to reform my code structure as i want to create this game as proffesionally and efficiently as possible.
    Now i have.
    CariocaTable which extends JFrame and in its constructor;
              // instantiate model, view and ,controller
              model = new CariocaModel();
              view = new CariocaPanel();
              controller = new CariocaController(model);
              // register View for Model events
              model.setCariocaListener( view );
              add(view, BorderLayout.CENTER);
              add(controller, BorderLayout.SOUTH);CariocaPanel in it has 4 player panels (4 player max game) which would contain their hands. then a center panel which contains the pickup and putdown piles.
    I am having alot of trouble implementing this pattern to my game (mybe im on the wrong track).
    the controller (in the ElevatorSimulation ) has 2 buttons which executes model method addPerson, thats about all the controller does which rocks my understanding.
    the model implements ElevatorSimulationListener (which extends all needed listeners) and has private variabels for all listeners.
    it then has a setElevatorSimulationListener(ElevatorSimulationListener listener) which is set with the view class.
    i have trouble understanding the communication between controller-view and model-view.. controller has to go threw model to talk to view but model only talks to view through listener methods
    public void lightTurnedOff( LightEvent lightEvent )
    //variable lightListener is the view.
          lightListener.lightTurnedOff( lightEvent );
       }i dont know where all the logic should go. i currently have model with the startGame method which creates players and cards, deals cards etc.
    am i on the right track. am i misunderstanding the design pattern? im sorry for the lengthy post, im having trouble understanding this and would like assistance with my understanding or even refer me to a book or website the would be helpful. if u would like more information please do ask.

    morgalr wrote:
    OK, I'll make a few assumptions and you can correct me if I am wrong on any of them:
    1 - the game is for 1 person to play against the computer
    2 - you may want to expend to multiplayer at some point
    3 - you would like to have the structure of the game as modular as possible to allow changesThank you for replying, yes thats exactly right.
    My approach now is to maintain the same structure as before instead of using the ElevatorSimulation as a guide.
    CariocaController will contain game logic and the static main method, and will update CariocaTable threw set methods.
    i will keep the revamped GUI classes, using what ive learned about using 2d instead of Swing Components, ive created an ImageLoader class which CariocaTable instantiates that loads all images into a hash map. PlayerPanel for each player, each panel contains variable Player, Pile hand, Pile downHand (objective of the game). Mybe i should get rid of the pile variables since the class Player already contains them?
    Its the drawing of the GUI that gets to me. Any other suggestions or ideas?

  • About flash Board game

    Hi all , i wanna ask a question regarding flash board game.
    i have an online flash application of chinese checkers board
    games that can be allowed up to 12 games rooms maximum.
    The question i wanted to ask is that if i got 12 game rooms ,
    do i need 12 different swf files for 2 players , another 12
    different swf files got 3 players , another 12 different swf files
    for 4 players and 6 players ?
    Please someone can enlighten me ? thank you

    I think this has more to do with the domain logic (how you
    structure your game and what you want it to do) than it does
    ActionScript.
    There is no reason you couldn't write a chinese checkers game
    with a dynamic amount of rooms all in one swf.

  • Help with Checkers

    hi
    i would like to build a checkers game(the rules are easier to code, will move to chess) heres how this works, this will be played on a browser(no downloading or anything) over the internet, with two players. the player can movie the pieces with either the mouse or the keyboard. Also they can rotate board( their own camera angle) to see the different positions of the board. this is not like the usual games where u get a bird-eyes view, but rather a 3D envirnoment with 3d pieces and a board, something like chessmaster just checkers. Also as it is over the internet, the game must load quickly.
    So now what should i use?? applet or webstart??? kindly list pros or cons?
    to design the pieces what should i do?? learn maya or 3d studio max or advanced photoshop?
    Is there a better way to accomplish this task???
    Ali

    yes, the files are cached on the users computer, on my computer (windows xp) the apps are stored here:
    C:\Documents and Settings\Weston\Application Data\Sun\Java\Deployment\javaws\cache
    the end user is never meant to interact with these files but rather they have an application on their start menu called "Java Web Start" where they can view all the webstart apps they have used an launch them from there. You are able to say whether the user can access the game from offline or not (this is specified in your jnlp file). When I say offline I mean they don't have to go to a web page to play the game, they can access it from their start menu, this has no effect on whether your game can connect to a server or not.
    Use the jarsigner utility to sign jars. Its free, no companies offer this service, you do it yourself.
    Here is 'webstart walkthrough': http://www.cokeandcode.com/info/webstart-howto.html
    If I were you I would not be so concerned about deployment at this point, learn java and some 3D graphics and when you have a game then make a decision.
    http://www.myjavaserver.com/~theanalogkid/servlets/app/mighty_bubbles.jnlp
    http://www.cyntaks.com/projects/asteroids/webstart/asteroids.jnlp <- my game :)
    http://www.puppygames.net/downloads/hallucinogenesis/hallucinogenesis.jnlp
    hope you don't mind malohkan: http://www.gamelizard.com/webstart/rimscape.php <- Malohkan's game
    those are a few good webstart games if you want to check them out. 2 of them make use of a 3D rendering api (mine and the super elvis game) so you can see an example of that too. Note that both of our games are 2D but use openGL which uses your 3D accelerator to create the graphics. So if you were going to write a 3D game with webstart it would launch like either of ours.

  • Checkers, Crowning of piece

    Hi,
    I am creating a checkers game and need some help. My board is created using a 2D array of type Player (I have a player class) - Player [][] men = new Player [8][8];
    Therefore the squares hollding black pieces are men[x][y] = player 2 and white are men[x][y] = player 1 (Player 1 and player 2 are both objects from player class).
    My problem is that I am unsure how to crown a piece when it lands on the relevant square. I am thinking along the lines of using a Piece class and having a maximum of
    4 pieces - WHITE_PIECE, WHITE_KING, BLACK_PIECE, BLACK_KING, but unsure how to relate these to my players.
    Any help with crowing would be extremely helpful, Thanks.

    jwenting wrote:
    A Game has 2 players and a Board. A Board has 100 squares (50 white, 50 black) ...not to nitpick (OK, yes I am), but it's actually an 8 x 8 board which comprises 64 squares. Of course only 1/2 the squares are permissible for play.
    But I agree with everything else you've said. To the OP: each piece can has several states (or as described above, characteristics) of which one of them (most likely a boolean) is "crowned". Its behavior of course will be dependent upon its state, and you'll have to code for this in your model. If you need more specific information, you'll have to ask a more specific question. Good luck!

  • Flex GUIs get a bad performance in normal screen mode when switched from full screen mode

    Hi, there :
    I encountered an odd situation and it is only happens on IE. Our project is a Flash 3D Game using Stage3D, and the Game's GUIs are created by CS6. When our game switch from the full screen( StageDisplayState.FULL_SCREEN_INTERACTIVE or StageDisplayState.FULL_SCREEN ) to normal screen ( StageDisplayState.NORMAL ), the performance of the Game GUIs decline to approximate a half FPS of full screen mode. But this condition is only happens on IE.
    The Game is normal screen when it is initialized and the performance is as same as fullscreen. The performance degradation only happens after switching to normal screen mode from full screen mode.
    p.s. : When the mouse is out of the view, the performance become better, from 20 fps up to 50 fps. But is still not as same as the original 60 fps.
    p.s. 2 : My colleague told me the Flash Pro CS6 be used to built a single swc file per GUI, and then package all ui swc files to one swc file by Flex Framework SDK( the command is "compc" ). and the IE version = 9.0.8112.16421, the Flash Player Version = 11.6.602.155.
    p.s. 3 : I have utilized Adobe Profiler Scout to observe the application, and I found that when it switches to normal screen mode from full screen mode, the time 「Waiting for GPU」 in 「Inactive」 grows up from 10ms to approximate 30ms which is triple. And in the 「Activity Sequence 」tab, it shows that the 「Waiting for GPU」 happens in the 「Copying to screen 」in 「DisplayObject List」.
    Thanks

    This does sound like a specific bug with IE. It would be great if you could file a bug report here (https://bugbase.adobe.com/), so we can get somebody to look into it.
    btw, Flex is really not a good framework for games - it's really slow and heavyweight. If you're just wanting some lightweight UI elements, you might want to check out the Feathers framework, which is built on top of Starling: http://feathersui.com/

  • Gui Interface

    Hi Im quite new to programming and thus need your help.
    public void click(int x, int y) {
    public void draw() {
    gui.drawGrid();
    gui.drawCircle(X,Y);
    gui.drawCross(A,B);
    public static void main(String s[])
    // Create the user game.
    TicTacToe game = new TicTacToe();
    // Associate the game and gui so they
    // may call each other's methods.
    TicTacToeWindow window = new TicTacToeWindow(game);
    game.gui = window;
    window.start();
    this plus another class which has already been defined is what i have to work with. In effect it is a tic tac toe game. I have already set up the Game board situation. Now all i need to know is how to convert the mouse clicks into drawing using the public void draw() method. Any help will be greatly appreciated. Thanks!

    Also, if you're truly a complete novice, you may want to look at the following resources for starting out:
    The Java&#153; Tutorial - A practical guide for programmers
    Essentials, Part 1, Lesson 1: Compiling & Running a Simple Program
    New to Java Center
    How To Think Like A Computer Scientist
    Introduction to Computer Science using Java
    The Java Developers Almanac 1.4
    JavaRanch: a friendly place for Java greenhorns
    jGuru
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Need some help in making a label disappear for certain time

    hi
    i need to make a program for my java class
    this is the question
    Design and implement a memory game. In this game you show the user a sequence of
    random integer numbers in the range of 0 to 99, and then ask him to type these
    numbers. Display how many he has remembered as a score. The level of game depends
    on how many numbers are there in the sequence. The duration of the display for the
    sequence is the speed. The user can adjust the level and the speed.
    my question is how to view the numbers for the game and make them disappear after certain time
    in need help with the syntax for it
    this is what i made so far
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.FlowLayout;
    import java.awt.Color;
    import javax.swing.JButton;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    import java.awt.*;
    class game extends JFrame implements ActionListener {
    public static final int WIDTH = 500;
    public static final int HEIGHT = 300;
    public static final int x = 3;
    public static final int y = 3000;
    public static void main(String[] args) {
    game gui = new game( );
    gui.setVisible(true);
    public game( )
    super("MEMORY GAME");
    setSize(WIDTH, HEIGHT);
    setDefaultCloseOperation(JFrame.EXIT_ON_…
    setLayout(new BorderLayout( ));
    JPanel buttonPanel = new JPanel( );
    buttonPanel.setBackground(Color.LIGHT_GR…
    buttonPanel.setLayout(new FlowLayout( ));
    JButton b1 = new JButton("MAKE IT HAREDER!!!");
    b1.addActionListener(this);
    buttonPanel.add(b1);
    JButton b2 = new JButton("MAKE IT FASTER!!!");
    b2.addActionListener(this);
    buttonPanel.add(b2);
    add(buttonPanel, BorderLayout.SOUTH);
    public void actionPerformed(ActionEvent e)
    String buttonString = e.getActionCommand( );
    if (buttonString.equals("MAKE IT HAREDER!!!"))
    else if (buttonString.equals("MAKE IT FASTER!!!"))
    }

    To post code, use the code tags -- [code]Your Code[/code] will display asYour CodeOr use the code button above the editing area and paste your code between the {code}{code} tags it generates.
    I strongly suggest you forget about the GUI part and first make a console application that fulfils the game specifications. If you have problems with this, you can post your questions in the New to Java section of these forums.
    db

Maybe you are looking for

  • Getting Error in opening a fla file in flash 8

    Hi I use flash 8 to edit my projects, recently I got a website related to music downloads and it was built in flash, now when I try to edit the fla file it opens up in flash 8 but I cannot see the library and when I edit it and make some changes in i

  • Iphone4s currently stuck in the recovery mode,

    hello guys, i tried to install the latest version that software update informed me which was 7.1 something today, normally for me it would just go directly to the loading bar, but this time it shut down and went to the recovery mode or whatever(just

  • Putting videos into iTunes library

    For some reason, my iTunes doesn't recognize .avi or other video files except for .mpg ones and it doesn't put them in the library. I have currently 3 video's, all .mpg. Can you help me please?

  • Fcp keeps quitting

    I am doing some basic editing and fcp has quit 4 times this hour. I am using a fcp 4.0 and editing SD footage from my sony avchd sr-5, (I converted in mpeg streamclip to mp4).... It started crashing as soon as I started working this morning. This has

  • How do I get a previous version of Firefox. Firefox 17 does not work with online banking

    How do I get a previous version of Firefox. Firefox 17 does not work with online banking edit