Swing games

I've recently started writting a few games in Java.... and used AWT components, ( all this involved was adding a Panel to a Frame and then painting to the Panel etc.)
I was just wondering if anyone could give me any ideas about how efficient Swing is for animation compared to using the AWT. eg...i know Swing offers automatic double buffering....are their any implications from the way this is achieved compared to implementing it yourself with the AWT?
Thanks

I don't think there would be any major difference. You probably already know that AWT component are "heavyweight", meaning they can eat more windowing system resources, but if you're only dealing with one panel that you continually draw on, then the difference would be negligible I believe.
Swing may be the tiniest bit slower due to some assumed internal overhead, but I've drawn custom graphics with swing and AWT, and haven't noticed any difference. Of course, I haven't written games...
A side note: if you're considering AWT, then I'm assuming you're using Java2? If so, you might take advantage of the Java 2D drawing libraries included in Java2. They offer lots of features (dithering for smooth edges, patterns for dotted lines, gradients, etc.)... all possibly useful for games.

Similar Messages

  • Distributing JRE with Java Swing Game

    I am developing some game using java swing. With the games I
    need to ship JRE because each user does not have JRE..
    So is there any other other solution.

    I forgot the name, but there is a very nice Installer tool that allows you to bundle your program with a JRE. Search the news groups.

  • Stream Corrupted while connection

    We have a java swing game that relies on connection with the server and that is established through object stream. Our problem is that in between game play �Stream Corrupted Exception� occurred and connection breaks.
    Is there a way we can avoid this, so that connection will carry on till the game finish?
    here is code at server for sending data
    public void sendMessage(CMessage cMessage)
         if(bIsClosed==false)
           try
                ObjectOutputStream objOutputStream=new ObjectOutputStream(socket.getOutputStream());
              objOutputStream.writeObject(cMessage);
              objOutputStream.flush();
           }catch(Exception e)
                bIsClosed=true;
                System.out.println("Error Sending Message "+cMessage.get_title()+e.toString());
              server.removeConnection( socket );
    }at receiving at client
    Object objMessageRecived;
    CMessage cMessageRecived;
    while(true)
         try
              objMessageRecived=(new ObjectInputStream(socket.getInputStream())).readObject();
              cMessageRecived=(CMessage)objMessageRecived;
              m_cWindow.handle_message(cMessageRecived);
    catch(IOException ex){
              System.out.println("Error in connection "+ex.toString());
              break;
         catch(ClassNotFoundException ce){System.out.println("Error in connection !!!!!! "+ce.toString());}
    }Thanks for all your suggestions,
    -Vidhi.

    thats not a problem bcause we r using it quiot regularly.
    and one more importent thing i like to say is after happening of this error actually connection is not breaked but client was't recived any message form server but can send am many as it can

  • Games y swing

    I'm creating a game where the board must be a map divided in hexagons. I've decided implements all the game with java , but i'm not sure what will be the best for the board, i want use Swing but creating hexagons is very difficult . any suggestion ????

    this program creates a Vector of hexagons of a given size in a Panel.
    import java.awt.*;
    import java.util.*;
    import java.math.*;
    import javax.swing.*;
    import java.awt.event.*;
    public class Hexagon extends JFrame
         myPan   pan  = new myPan();
    public Hexagon()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);}});
         setBounds(10,10,600,400);
         getContentPane().add(pan,BorderLayout.CENTER);
         setVisible(true);
    public class myPan extends JPanel
         Vector  vx   = new Vector();
         int     ts   = 0;
    public myPan()
    private void create_hexagons(int x, int y,int d)
         Polygon po = new Polygon();
         int w = d;
         int h = d;
         int p = (int)Math.sqrt(d/2*d/2/3);
         int x1 = x-2*p;
         int y1 = y-h/2;
         po.addPoint(x1,y1+h/2);
         po.addPoint(x1+p,y1);
         po.addPoint(x1+w-p,y1);
         po.addPoint(x1+w,y1+h/2);
         po.addPoint(x1+w-p,y1+h);
         po.addPoint(x1+p,y1+h);
         vx.add(po);
         int nx = x+2*w-2*p;
         int ny = y+h/2;
         if (nx < pan.getWidth()+p) create_hexagons(nx,y,d);
              else if (ny < pan.getHeight()+h/2)
                   if (ts == 0) ts = w-p; else ts = 0;
                   create_hexagons(ts,ny,d);
    public void paint(Graphics g)
         if (vx.size() == 0) create_hexagons(0,0,26);
         Graphics2D G = (Graphics2D)g;
         G.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);          
         for (int i=0; i < vx.size();i++)
              Polygon p = (Polygon)vx.get(i);
              G.setColor(Color.orange);
              G.fillPolygon(p);
              G.setColor(Color.gray);
              G.drawPolygon(p);
         G.dispose();
    public static void main (String[] args) 
         new Hexagon();
    Noah

  • Game loop using Swing?

    Hey everyone. My simple game engine currently uses Swing for the frames and components, but uses an AWT Canvas for the actual game display. I'm trying to figure out how to change entirely to Swing components.
    Here's basically how I've laid out my game loop thread using Canvas:
    1. Do calculations since last loop
    2. Get Graphics2D object via the canvas' BufferStrategy object
    3. Clear the background with white.
    4. Call the draw(Graphics2D) method.
    5. Dispose & flip the buffer.
    6. Call the update(long) method using the calculations from step 1.
    7. Sleep for a bit.
    8. Repeat loopThis is working very smoothly right now and is very flexible for subclassing. But since it's a mix of Swing & AWT there are some problems here and there and I feel it could be improved by keeping it Swing-only.
    What's the best way to implement a similar game thread loop using a Swing component?
    Code can be supplied if needed. Thanks!

    Use a JPanel instead of a Canvas.

  • Applet 2d games swing or not swing?

    I saw this in the java applet tutorials:
    "An applet may extend java.applet.Applet when it makes no use of Swing's GUI components. This may be the case if the applet does all its own rendering using the Java graphics libraries (such as with graphing or gaming) and/or uses only AWT components. "
    I�m newbie to Java Applet programming and would like to learn program a 2D game in java, a simple adventure game in which you move around a figure on the screen with the keyboard. What is the best way to go about, with or without swing or another way? Is there a new way to do things perhaps?
    Yah I know I need to learn the basics first but always good to know what to learn further ahead :-)

    If I were you I wouldn't program this as an applet at all. Make it a standalone app. Making it an applet will just make testing more difficult. You can always refactor it later to turn it into an applet (or more likely, write an applet that's just a wrapper around your game).
    Swing is basically a set of GUI tools. Are you planning extensive use of GUI widgets in your game?
    Edited by: paulcw on Feb 28, 2008 12:23 PM

  • Urgent Help Required for Connect Four Game

    Hi all,
    I am a student and I have a project due 20th of this month, I mean May 20, 2007 after 8 days. The project is about creating a Connect Four Game. I have found some code examples on the internet which helped me little bit. But there are lot of problems I am facing developing the whole game. I have drawn the Board and the two players can play. The players numbers can fill the board, but I have problem implementing the winner for the game. I need to implement the hasWon() method for Horizontal win, Vertical win and Diagonal win. I also found some code examples on the net but I was unable to make it working. I have 5 classes and one interface which I m implementing. The main problem is how to implement the hasWon() method in the PlayGame class below with Horizontal, vertical and diagonal moves.
    Sorry there is so much code.
    This the interface I must implement, but now I am only implementing the int move() of this interface. I will implement the rest later after solving the winner problem with your help.
    Interface code..............
    interface Player {
    void init (Boolean color);
    String name ();
    int move ();
    void inform (int i);
    Player1 class......................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class Player1 implements Player
    public Player1()
    public int move()
    Scanner scan = new Scanner(System.in);
    // BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
    int player1;
    System.out.println ("What is your Number, player 1?");
    player1 = scan.nextInt();
    System.out.println ("Hey number"+player1+" are you prepared to CONNECT FOUR");
    System.out.println();
    return player1;
    //Player.move();
    //return player1;
    }//end move method
    public void init (Boolean color)
    public void inform (int i)
    public String name()
    return "Koonda";
    }//end player1 class
    Player2 class...........................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class Player2 implements Player
    public int move()
    //int cup0,cup1,cup2,cup3,cup4,cup5,cup6;
    // cup0=5;cup1=5;cup2=5;cup3=5;cup4=5;cup5=5;cup6=5;
    //int num1, num2;
    Scanner scan = new Scanner(System.in);
    // BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
    int player2;
    System.out.println ("What is your Number, player 2?");
    player2 = scan.nextInt();
    System.out.println ("Hey "+player2+" are you prepared to CONNECT FOUR");
    System.out.println();
    //return player1;
    return player2;
    }//end move method
    public void init (Boolean color)
    public void inform (int i)
    public String name()
    return "malook";
    }//end player1 class
    PlayGame class which contains all the functionality.........................................................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class PlayGame
    //Player player1;
    //Player player2;
    int [][]ConnectFourArray;
    boolean status;
    int winner;
         int player1;
         int player2;
         public PlayGame()
              //this.player1 = player1;
              //this.player2 = player2;
         public void StartGame()
         try{
         // int X = 0, Y = 0;
         //int value;
         int cup0,cup1,cup2,cup3,cup4,cup5,cup6;
    cup0=5;cup1=5;cup2=5;cup3=5;cup4=5;cup5=5;cup6=5;
         int[][] ConnectFourArray = new int[6][7];
         int num1, num2;
         for(int limit=21;limit!=0;limit--)
    BufferedReader selecter = new BufferedReader (new InputStreamReader(System.in));
    String column1;
    System.out.println();
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    System.out.println ("Please Select a column of 0 through 6 ");
    column1 = selecter.readLine();
    num1= Integer.parseInt(column1);
    System.out.println();
    if (num1==0){
    ConnectFourArray[cup0][0]=1;
    cup0=cup0-1;
    else if (num1==1){
    ConnectFourArray[cup1][1]=1;
    cup1=cup1-1;
    else if (num1==2){
    ConnectFourArray[cup2][2]=1;
    cup2=cup2-1;
    else if (num1==3){
    ConnectFourArray[cup3][3]=1;
    cup3=cup3-1;
    else if (num1==4){
    ConnectFourArray[cup4][4]=1;
    cup4=cup4-1;
    else if (num1==5){
    ConnectFourArray[cup5][5]=1;
    cup5=cup5-1;
    else if (num1==6){
    ConnectFourArray[cup6][6]=1;
    cup6=cup6-1;
    System.out.println();
    BufferedReader selecter2 = new BufferedReader (new InputStreamReader(System.in));
    String column2;
    System.out.println();
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    System.out.println ("Please Select a column of 0 through 6 ");
    column1 = selecter.readLine();
    num1= Integer.parseInt(column1);
    System.out.println();
    if (num1==0){
    ConnectFourArray[cup0][0]=2;
    cup0=cup0-1;
    else if (num1==1){
    ConnectFourArray[cup1][1]=2;
    cup1=cup1-1;
    else if (num1==2){
    ConnectFourArray[cup2][2]=2;
    cup2=cup2-1;
    else if (num1==3){
    ConnectFourArray[cup3][3]=2;
    cup3=cup3-1;
    else if (num1==4){
    ConnectFourArray[cup4][4]=2;
    cup4=cup4-1;
    else if (num1==5){
    ConnectFourArray[cup5][5]=2;
    cup5=cup5-1;
    else if (num1==6){
    ConnectFourArray[cup6][6]=2;
    cup6=cup6-1;
    System.out.println();
    System.out.println();
    catch (Exception E){
    System.out.println("Error with input");
    System.out.println("Would you like to play again");
    try{
    String value;
    BufferedReader reader = new BufferedReader (new InputStreamReader(System.in));
    // Scanner scan = new Scanner(System.in);
    System.out.println("Enter yes to play or no to quit");
    // value = scan.nextLine();
    // String value2;
    value = reader.readLine();
    //value2 = reader.readLine();
    if (value.equals("yes"))
    System.out.println("Start again");
    StartGame(); // calling the StartGame method to play a game once more
    else if (value.equals("no"))
    System.out.println("No more games to play");
    // System.exit(0);
    else
    System.exit(0);
    System.out.println();
    catch (Exception e){
    System.out.println("Error with input");
    finally
    System.out.println(" playing done");
    //StartGame();
    //check for horizontal win
    public int hasWon()
    int status = 0;
    for (int row=0; row<6; row++)
    for (int col=0; col<4; col++)
    if (ConnectFourArray[col][row] != 0 &&
    ConnectFourArray[col][row] == ConnectFourArray[col+1][row] &&
    ConnectFourArray[col][row] == ConnectFourArray[col+2][row] &&
    ConnectFourArray[col][row] == ConnectFourArray[col+3][row])
    //status = true;//int winner;
    if(status == player1)
    System.out.println("Player 1 is the winner");
    else if(status == player2)
    System.out.println("Player 2 is the winner" );
    }//end inner for loop
    }// end outer for loop
    } // end method Winner
    return status;
    }//end class
    ClassConnectFour which designs the board........................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class ClassConnectFour
         //Player player1;
         //Player player2;
         public ClassConnectFour()
              //this.player1 = player1;
    public void DrawBoard()
    int[][] ConnectFourArray = new int[6][7] ;
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    }//end class
    TestConnetFour class which uses most of the above class..................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class TestConnectFour
    public static void main(String[] args)
    ClassConnectFour cf = new ClassConnectFour();
    cf.DrawBoard();
    Player1 player1 = new Player1();
    Player2 player2 = new Player2();
    player1.move();
    player2.move();
    System.out.println("Number 1 belongs to player " + player1.name());
    System.out.println("Number 2 belongs to player " + player2.name());
    PlayGame pg = new PlayGame();
    pg.StartGame();
    pg.hasWon();
    //pg.Play();
    //System.out.println(player.name());
    //System.out.println(player2.name());
    }// end main
    }//end class
    I am sorry for all this junk code but I only understand it this way. Your urgent help is required. Looking forward to your reply.
    Thanks in advance.
    Koonda
    //

    Hi,
    Thanks for your help but I really don't understand the table lookup algorithm. Could you please send me some code to implement that.
    I will send you the formatted code as well
    Thanks for your help.
    looking forward to your reply.
    Koonda
    Hi all,
    I am a student and I have a project due 20th of this month, I mean May 20, 2007 after 8 days. The project is about creating a Connect Four Game. I have found some code examples on the internet which helped me little bit. But there are lot of problems I am facing developing the whole game. I have drawn the Board and the two players can play. The players numbers can fill the board, but I have problem implementing the winner for the game. I need to implement the hasWon() method for Horizontal win, Vertical win and Diagonal win. I also found some code examples on the net but I was unable to make it working. I have 5 classes and one interface which I m implementing. The main problem is how to implement the hasWon() method in the PlayGame class below with Horizontal, vertical and diagonal moves.
    Sorry there is so much code.
    This the interface I must implement, but now I am only implementing the int move() of this interface. I will implement the rest later after solving the winner problem with your help.
    Interface code..............
    interface Player {
    void init (Boolean color);
    String name ();
    int move ();
    void inform (int i);
    Player1 class......................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class Player1 implements Player
    public Player1()
    public int move()
    Scanner scan = new Scanner(System.in);
    // BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
    int player1;
    System.out.println ("What is your Number, player 1?");
    player1 = scan.nextInt();
    System.out.println ("Hey number"+player1+" are you prepared to CONNECT FOUR");
    System.out.println();
    return player1;
    //Player.move();
    //return player1;
    }//end move method
    public void init (Boolean color)
    public void inform (int i)
    public String name()
    return "Koonda";
    }//end player1 class
    Player2 class...........................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class Player2 implements Player
    public int move()
    //int cup0,cup1,cup2,cup3,cup4,cup5,cup6;
    // cup0=5;cup1=5;cup2=5;cup3=5;cup4=5;cup5=5;cup6=5;
    //int num1, num2;
    Scanner scan = new Scanner(System.in);
    // BufferedReader stdin = new BufferedReader (new InputStreamReader(System.in));
    int player2;
    System.out.println ("What is your Number, player 2?");
    player2 = scan.nextInt();
    System.out.println ("Hey "+player2+" are you prepared to CONNECT FOUR");
    System.out.println();
    //return player1;
    return player2;
    }//end move method
    public void init (Boolean color)
    public void inform (int i)
    public String name()
    return "malook";
    }//end player1 class
    PlayGame class which contains all the functionality.........................................................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class PlayGame
    //Player player1;
    //Player player2;
    int [][]ConnectFourArray;
    boolean status;
    int winner;
    int player1;
    int player2;
    public PlayGame()
    //this.player1 = player1;
    //this.player2 = player2;
    public void StartGame()
    try{
    // int X = 0, Y = 0;
    //int value;
    int cup0,cup1,cup2,cup3,cup4,cup5,cup6;
    cup0=5;cup1=5;cup2=5;cup3=5;cup4=5;cup5=5;cup6=5;
    int[][] ConnectFourArray = new int[6][7];
    int num1, num2;
    for(int limit=21;limit!=0;limit--)
    BufferedReader selecter = new BufferedReader (new InputStreamReader(System.in));
    String column1;
    System.out.println();
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    System.out.println ("Please Select a column of 0 through 6 ");
    column1 = selecter.readLine();
    num1= Integer.parseInt(column1);
    System.out.println();
    if (num1==0){
    ConnectFourArray[cup0][0]=1;
    cup0=cup0-1;
    else if (num1==1){
    ConnectFourArray[cup1][1]=1;
    cup1=cup1-1;
    else if (num1==2){
    ConnectFourArray[cup2][2]=1;
    cup2=cup2-1;
    else if (num1==3){
    ConnectFourArray[cup3][3]=1;
    cup3=cup3-1;
    else if (num1==4){
    ConnectFourArray[cup4][4]=1;
    cup4=cup4-1;
    else if (num1==5){
    ConnectFourArray[cup5][5]=1;
    cup5=cup5-1;
    else if (num1==6){
    ConnectFourArray[cup6][6]=1;
    cup6=cup6-1;
    System.out.println();
    BufferedReader selecter2 = new BufferedReader (new InputStreamReader(System.in));
    String column2;
    System.out.println();
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    System.out.println ("Please Select a column of 0 through 6 ");
    column1 = selecter.readLine();
    num1= Integer.parseInt(column1);
    System.out.println();
    if (num1==0){
    ConnectFourArray[cup0][0]=2;
    cup0=cup0-1;
    else if (num1==1){
    ConnectFourArray[cup1][1]=2;
    cup1=cup1-1;
    else if (num1==2){
    ConnectFourArray[cup2][2]=2;
    cup2=cup2-1;
    else if (num1==3){
    ConnectFourArray[cup3][3]=2;
    cup3=cup3-1;
    else if (num1==4){
    ConnectFourArray[cup4][4]=2;
    cup4=cup4-1;
    else if (num1==5){
    ConnectFourArray[cup5][5]=2;
    cup5=cup5-1;
    else if (num1==6){
    ConnectFourArray[cup6][6]=2;
    cup6=cup6-1;
    System.out.println();
    System.out.println();
    catch (Exception E){
    System.out.println("Error with input");
    System.out.println("Would you like to play again");
    try{
    String value;
    BufferedReader reader = new BufferedReader (new InputStreamReader(System.in));
    // Scanner scan = new Scanner(System.in);
    System.out.println("Enter yes to play or no to quit");
    // value = scan.nextLine();
    // String value2;
    value = reader.readLine();
    //value2 = reader.readLine();
    if (value.equals("yes"))
    System.out.println("Start again");
    StartGame(); // calling the StartGame method to play a game once more
    else if (value.equals("no"))
    System.out.println("No more games to play");
    // System.exit(0);
    else
    System.exit(0);
    System.out.println();
    catch (Exception e){
    System.out.println("Error with input");
    finally
    System.out.println(" playing done");
    //StartGame();
    //check for horizontal win
    public int hasWon()
    int status = 0;
    for (int row=0; row<6; row++)
    for (int col=0; col<4; col++)
    if (ConnectFourArray[col][row] != 0 &&
    ConnectFourArray[col][row] == ConnectFourArray[col+1][row] &&
    ConnectFourArray[col][row] == ConnectFourArray[col+2][row] &&
    ConnectFourArray[col][row] == ConnectFourArray[col+3][row])
    //status = true;//int winner;
    if(status == player1)
    System.out.println("Player 1 is the winner");
    else if(status == player2)
    System.out.println("Player 2 is the winner" );
    }//end inner for loop
    }// end outer for loop
    } // end method Winner
    return status;
    }//end class
    ClassConnectFour which designs the board........................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class ClassConnectFour
    //Player player1;
    //Player player2;
    public ClassConnectFour()
    //this.player1 = player1;
    public void DrawBoard()
    int[][] ConnectFourArray = new int[6][7] ;
    for ( int row=0; row < ConnectFourArray.length; row++ ){
    System.out.print("Row " + row + ": ");
    for ( int col=0; col < ConnectFourArray[row].length; col++ )
    System.out.print( ConnectFourArray[row][col] + " ");
    System.out.println();
    System.out.println();
    }//end class
    TestConnetFour class which uses most of the above class..................
    import java.util.*;
    import java.io.*;
    import javax.swing.*;
    public class TestConnectFour
    public static void main(String[] args)
    ClassConnectFour cf = new ClassConnectFour();
    cf.DrawBoard();
    Player1 player1 = new Player1();
    Player2 player2 = new Player2();
    player1.move();
    player2.move();
    System.out.println("Number 1 belongs to player " + player1.name());
    System.out.println("Number 2 belongs to player " + player2.name());
    PlayGame pg = new PlayGame();
    pg.StartGame();
    pg.hasWon();
    //pg.Play();
    //System.out.println(player.name());
    //System.out.println(player2.name());
    }// end main
    }//end classI am sorry for all this junk code but I only understand it this way. Your urgent help is required. Looking forward to your reply.
    Thanks in advance.
    Koonda

  • Swing and Active rendering problem

    Hopefully this is the right place to post. I have a problem with active rendering and swing. Basically my code below messes up when I start rendering the swing either using repaint() or paint(g).
    If I use repaint() then the gui flickers like mad and if I use paint(g) then I get deadlocks when typing into the textbox.
    Any help would be great for what am I doing wrong. How do I solve this problem?
    public GuiWindow() {
              try {
                   guiImage = ImageIO.read(this.getClass().getResource("Images/Gui2.png"));
              } catch (Exception e) {}
              this.setPreferredSize(new Dimension(800, 600));
              this.setUndecorated(true);
              this.setIgnoreRepaint(true);
              this.setResizable(false);
              this.addKeyListener(kl);
              this.setFocusable(true);
              this.requestFocus();
              this.setTitle("PWO");
              JPanel panel = new JPanel()
              public void paintComponent(Graphics g)
              //Scale image to size of component
                   super.paintComponent(g);
                   Dimension d = getSize();
                   g.drawImage(guiImage, 0, 0, d.width, d.height, null);
                   this.setIgnoreRepaint(true);
                            //draw background for the gui
              JTextField Name = new JTextField(20);
              panel.add(Name);
              this.setContentPane(panel);
                    myRenderingLoop();
    public void myRenderingLoop() {
              int fps = 20;
              long startTime;
              int frameDelay = 1000 / fps;
              this.createBufferStrategy(2);
              BufferStrategy myStrategy = this.getBufferStrategy();
              Graphics2D g;
              while (!done) {
                   startTime = System.currentTimeMillis();          
                   do {
                        do {
                             g = (Graphics2D)myStrategy.getDrawGraphics();
                             this.repaint();
                             this.render(g); //render the game
                             g.dispose();
                        } while (myStrategy.contentsRestored());
                        myStrategy.show();
                        Toolkit.getDefaultToolkit().sync();
                   } while (myStrategy.contentsLost());
                   while (System.currentTimeMillis() - startTime < frameDelay) {
                        try {
                             Thread.sleep(15);
                        } catch (InterruptedException ex){}
         }Edited by: Aammbi on Apr 6, 2008 7:05 PM

    I really have no idea what your code is trying to do, but a few comments.
    1) There is no need to use a BufferStrategy since Swing is double buffered automatically
    2) Don't use a while loop with a Thread.sleep(). Chances are the GUI EDT is sleeping which makes the GUI unresponsive
    3) Use a Swing Timer for animation.
    If you need further help then you need to create a [Short, Self Contained, Compilable and Executable, Example Program (SSCCE)|http://homepage1.nifty.com/algafield/sscce.html], that demonstrates the incorrect behaviour.

  • Puzzle Game and new Game Problem

    Hello Java Programmers,
    Once again I have encountered a problem with my ongoing puzzle game. I have completed it all. Now I want my user to be able to start a new game in after they win. I tried repaint and update method with JFrame but it deosn't reshuffle the buttons. How can I do that. The code geos below.
    [/b]
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.JOptionPane;
    public class PuzzleGame{
       String[] btn_Labels = {"1","2","3","4","5","6","7","8","9",
                            "10","11","12","13","14","15"," "};
       String[] labels = {"1","2","3","4","5","6","7","8","9",
                            "10","11","12","13","14","15"};
       private final int ONE = 1, TWO = 2, THREE = 3, FIVE = 5;
       private boolean WIN_STATE = false; 
       private JButton b[];
       public String clicked_btn_label = "";
       //Constructor method.
       public PuzzleGame(){
          showSplashScreen();
          initGame();
       public static void main(String args[]){
          PuzzleGame game = new PuzzleGame();
       //When a new Game started labels of buttons are shuffled using this method.
       public void shuffleNumbers(){
          String temp = null;   
          for(int j=0; j<16; j++){
          int k = (int)(Math.random()*16);
          temp = btn_Labels[j];
          btn_Labels[j] = btn_Labels[k];
          btn_Labels[k] = temp;           
       //Game initialization method.
       public void initGame(){
          b = new JButton[16];
          JPanel p = new JPanel();
          JFrame frame = new JFrame();
          shuffleNumbers();
          for(int i=0; i<16; i++){
             b[i] = new JButton();
             b.setText(btn_Labels[i]);
    b[i].setActionCommand(""+(i+1));
    for(int i=0; i<16; i++){
    b[i].addActionListener( new ActionListener(){
    public void actionPerformed(ActionEvent e){
    clicked_btn_label =(String)e.getActionCommand();
    doSwapping();
    checkWin();
    p.add(b[i]);
    p.setLayout(new GridLayout(4,4));
    frame.getContentPane().add(p);
    frame.addWindowListener(new WindowAdapter(){
    public void windowClosing(WindowEvent e){
    System.exit(0);
    Dimension dm = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (dm.width - 230)/2;
    int y = (dm.height - 240)/2;
    frame.setBounds(x,y,320,240);
    frame.setSize(340,240);
    frame.setVisible(true);
    //This method swaps the clicked button with the empty button if it doesn't violate rule.
    public void doSwapping(){
    int num = Integer.parseInt(clicked_btn_label);
    String temp;
    if( (num + ONE <= 16) && b[num].getText() == " " && num % 4 != 0){
    temp = b[num].getText();
    b[num].setText(b[num-ONE].getText());
    b[num-ONE].setText(temp);
    else if((num - TWO >= 0) && b[num-TWO].getText() == " " && ((num - ONE) % 4 != 0)){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num-TWO].getText());
    b[num-TWO].setText(temp);
    else if( (num + THREE < 16) && b[num+THREE].getText() == " "){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num+THREE].getText());
    b[num+THREE].setText(temp);
    else if( (num - FIVE >= 0) && b[num-FIVE].getText() == " "){
    temp = b[num-ONE].getText();
    b[num-ONE].setText(b[num-FIVE].getText());
    b[num-FIVE].setText(temp);
    // else{}
    public void checkWin(){
    WIN_STATE = true;
    for(int i=0; i<15; i++){
    if( b[i].getText() != labels[i])
    WIN_STATE = false;
    if(WIN_STATE == true){
    JOptionPane.showMessageDialog(null,"Congratulations You Have won the Game!","You Win",JOptionPane.INFORMATION_MESSAGE);
         initGame();
    public void showSplashScreen(){
    JWindow w = new JWindow();
    JPanel p = (JPanel)w.getContentPane();
    JLabel l = new JLabel(new ImageIcon("splash.jpg"));
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    int x = (d.width - 230)/2;
    int y = (d.height - 240)/2;
    p.add(l);
    w.setBounds(x,y,320,240);
    w.setVisible(true);
    try{
    Thread.sleep(10000);
    catch(Exception e){
    w.setVisible(false);
    [/b]                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Sorry for violation. I would like to add a menubar to the application containing a single menu button for new game. adding a menubar is simple but how can i reshuffle the buttons using methods like update etc. or any other way.

  • Game of Life display problem

    The Rules of Game of Life
    For a space that is 'populated':
    Each cell with one or no neighbors dies, as if by loneliness.
    Each cell with four or more neighbors dies, as if by overpopulation.
    Each cell with two or three neighbors survives.
    For a space that is 'empty' or 'unpopulated'
    Each cell with three neighbors becomes populated.
    I have three classes: Cell, BoardComponent, and GameViewer
    I got few problems in my code: 1. the button shows wrongly, 2. without the button, there is always a dot on the upper-left corner, which is not on purpose, 3, after click the mouse to initialize few dots, nothing happened
    How could I fix those problems?
    My Code:
    1. Cell:
    import java.awt.Rectangle;
    public class Cell extends Rectangle{
         public Cell(int x, int y, int side)
              super(x, y, side, side);
    }2. BoardComponent:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JComponent;
    import com.sun.jdi.event.Event;
    public class BoardComponent extends JComponent{
         public BoardComponent()
              for(int i = 0; i < ROW; i++)
                   for(int j = 0; j < COL; j++)
                        board[i][j] = new Cell(i*SIDE, j*SIDE, SIDE);
         public void paint(Graphics g)
              Graphics2D g2 = (Graphics2D)g;
              for(int i = 0; i < ROW; i++)
                   for(int j = 0; j < COL; j++)
                        g2.draw(board[i][j]);
         public void initialize(int x, int y)
              Graphics g = getGraphics();
              Graphics2D g2 = (Graphics2D) g;
              if(g2.getColor().equals(Color.BLUE))
                   g2.getBackground();
              else
                   g2.setColor(Color.BLUE);
                   g.fillOval(mouseX, mouseY, 10, 10);
         public void generate()
              int count = 0;
              for(int i = 0; i < ROW-2; i++)
                   for(int j = 0; j < COL-2; j++)
                        for(int m = 0; m < 2; m++)
                             for(int n = 0; n < 2; n++)
                                  if(m!=0 || n !=0)
                                       if(!(board[i+m][j+n].isEmpty()))
                                            count++;
                        if(count == 3 || count < 2 || count > 4)
                             initialize(i*SIDE, j*SIDE);
         private int mouseX, mouseY;
         private boolean mouseclicked = false;
         public static final int ROW = 40;
         public static final int COL = 40;
         private Cell[][] board = new Cell[ROW][COL];
         public static final int SIDE = 14;
    }3. GameViewer:
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    public class GameViewer extends JFrame{
         public static void main(String[] args)
              final BoardComponent game = new BoardComponent();
              class MouseClickListener extends MouseAdapter
                   public void mouseClicked(MouseEvent event)
                        int x = event.getX();
                        int y = event.getY();
                        game.initialize(x, y);
              MouseAdapter listener = new MouseClickListener();
              game.addMouseListener(listener);
              JButton button = new JButton("Start");
             class TimerListener implements ActionListener
                   public void actionPerformed(ActionEvent event)
                        game.generate();
            ActionListener timer = new TimerListener();
            button.setSize(40, 10);
            button.setLocation(250, 500);
            button.addActionListener(timer);
            final int DELAY = 500;
            Timer t = new Timer(DELAY, timer);
            t.start();  
            JFrame window = new JFrame();
            window.setSize(600, 600);
            window.setTitle("Life of Game");
            window.setDefaultCloseOperation(EXIT_ON_CLOSE);
            window.add(game);
            window.add(button);
            window.setVisible(true);
    }Thanks a million.

    As already said, you should override paintComponent(), not paint(), and don't forget to call the superclass's paintComponent() method.
    public void paintComponent(Graphics g)
       super.paintComponent(g);
    }As for this method:
         public void initialize(int x, int y)
              Graphics g = getGraphics();
              Graphics2D g2 = (Graphics2D) g;
              if(g2.getColor().equals(Color.BLUE))
                   g2.getBackground();
              else
                   g2.setColor(Color.BLUE);
                   g.fillOval(mouseX, mouseY, 10, 10);
         }You really shouldn't be doing any painting outside the paintComponent() method.
    Finally, your GameViewer class extends JFrame, but yet you are creating another JFrame in the main method. This doesn't make sense.

  • How to develop a GUI in my game

    Hi,
    I'm working on a multiplayer game in Java 1.4. This is more like a prototype than a commercial quality game, and since the focus of my work is on the networking capabilities of the game, I want to spend the least possible time with mundane things like how to type information and select things on my game...in other words, having a GUI that can provide the game with a menu/submenus, buttons, textfields and the like.
    I've done several Swing applications before but this is different, since the event loop is provided by me (as any other game) and I'm using "active rendering" to display the graphics on screen.
    Does anyone knows how can I use the Swing (or AWT) components in my game?
    Thanks in advance.
    Gabriel

    Hi,
    Thanks for the ansewr. I've been doing an example and I could get my Swing dialog to appear in the screen.
    Below is thesource code of my example. It works but it seems to me that the animation of the square is flickering somehow (I think is double buffered) and the frame rate is somewhat low.
    I would like to know how to improve those things in the example so I could use it in my game.
    Regards,
    Gabriel
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import com.sun.j3d.utils.timer.*;
    public class ActiveSwingTest implements Runnable {
      static final int VEL = 1;
      // Number of frames with a delay of 0 ms before the animation thread yields
      // to other running threads.
      private static final int NO_DELAYS_PER_YIELD = 16;
      // no. of frames that can be skipped in any one animation loop
      // i.e the games state is updated but not rendered
      private static int MAX_FRAME_SKIPS = 5; // was 2;
      JFrame f;
      JPanel panel;
      Image backBuffer;
      JDialog dialog;
      private long gameStartTime;
      private long prevStatsTime;
      private boolean running;
      private Graphics2D graphics;
      private long period;
      private long framesSkipped = 0;
      int x = 0;
      int y = 0;
      int vx = VEL;
      int vy = VEL;
      public ActiveSwingTest() {
        initGraphics();
      public void initGraphics() {
        panel = new JPanel();
        panel.setPreferredSize(new Dimension(800, 600));
        panel.setFocusable(true);
        panel.requestFocus();
        panel.setIgnoreRepaint(true);
        readyForTermination();
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(panel);
        f.setIgnoreRepaint(true);
        f.setResizable(false);
        f.pack();
        backBuffer = createBackBuffer();
        if(backBuffer == null) {
          return;
        f.setVisible(true);
      public void run() {
        long timeDiff = 0;
        long overSleepTime = 0L;
        int noDelays = 0;
        long excess = 0L;
        gameStartTime = J3DTimer.getValue();
        prevStatsTime = gameStartTime;
        long beforeTime = gameStartTime;
        running = true;
        graphics = (Graphics2D) backBuffer.getGraphics();
        while(running) {
          update(timeDiff);
          render(graphics);
          paintScreen();
          long afterTime = J3DTimer.getValue();
          timeDiff = afterTime - beforeTime;
          long sleepTime = (period - timeDiff) - overSleepTime;
          if(sleepTime > 0) { // some time left in this cycle
            try {
              Thread.sleep(sleepTime / 1000000L); // nano -> ms
            catch(InterruptedException ex) {}
            overSleepTime = (J3DTimer.getValue() - afterTime) - sleepTime;
          else { // sleepTime <= 0; the frame took longer than the period
            excess -= sleepTime; // store excess time value
            overSleepTime = 0L;
            if(++noDelays >= NO_DELAYS_PER_YIELD) {
              Thread.yield(); // give another thread a chance to run
              noDelays = 0;
          beforeTime = J3DTimer.getValue();
          /* If frame animation is taking too long, update the game state
             without rendering it, to get the updates/sec nearer to
             the required FPS. */
          int skips = 0;
          while((excess > period) && (skips < MAX_FRAME_SKIPS)) {
            excess -= period;
            update(timeDiff); // update state but don't render
            skips++;
          framesSkipped += skips;
        System.exit(0); // so window disappears
      private void showDialogo() {
        if ( dialog == null ) {
          dialog = new JDialog(f, "Example dialog", true);
          final JTextField t = new JTextField("hello");
          JButton bok = new JButton("OK");
          bok.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                  System.out.println("text="+t.getText());
                  dialog.setVisible(false);
                  dialog.dispose();
                  dialog = null;
          JButton bcancel = new JButton("Cancel");
          bcancel.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                      dialog.setVisible(false);
          final Container c = dialog.getContentPane();
          c.setLayout(new BorderLayout());
          c.add(t, BorderLayout.CENTER);
          final JPanel buttonPanel = new JPanel();
          buttonPanel.add(bok);
          buttonPanel.add(bcancel);
          c.add(buttonPanel, BorderLayout.PAGE_END);
          dialog.pack();
          dialog.setLocationRelativeTo(f);
          dialog.setVisible(true);
        else {
          dialog.setVisible(true);
      private void paintScreen() {
        // use active rendering to put the buffered image on-screen
        try {
          final Graphics g = panel.getGraphics();
          if(g != null) {
            g.drawImage(backBuffer, 0, 0, null);
          g.dispose();
        catch(Exception e) {
          System.out.println("Graphics context error: " + e);
      private Image createBackBuffer() {
        final Image dbImage = panel.createImage(800, 600);
        if(dbImage == null) {
          System.out.println("could not create the backbuffer image!");
        return dbImage;
      private void readyForTermination() {
        panel.addKeyListener(new KeyAdapter() {
          // listen for esc, q, end, ctrl-c on the canvas to
          // allow a convenient exit from the full screen configuration
          public void keyPressed(KeyEvent e) {
            int keyCode = e.getKeyCode();
            if((keyCode == KeyEvent.VK_ESCAPE) || (keyCode == KeyEvent.VK_Q) ||
               (keyCode == KeyEvent.VK_END) ||
               ((keyCode == KeyEvent.VK_C) && e.isControlDown())) {
              running = false;
            else if ( keyCode == KeyEvent.VK_D ) {
              showDialogo();
      private void update(long dt) {
        x += vx;
        y += vy;
        if ( x < 0 ) {
          x = 0;
          vx = VEL;
        else if ( x > 700 ) {
          x = 700;
          vx = -VEL;
        if ( y < 0 ) {
          y = 0;
          vy = VEL;
        else if ( y > 500 ) {
          y = 500;
          vy = -VEL;
      private void render(Graphics2D g) {
        g.setColor(Color.RED);
        g.fillRect(0, 0, 800, 600);
        g.setColor(Color.WHITE);
        g.fillRect(x, y, 100, 100);
      public static void main(String[] args) {
        ActiveSwingTest test = new ActiveSwingTest();
        new Thread(test).start();
    }

  • How to create a turn-based multiplayer online game?

    Hello. This is my first time here. I am familiar with programming games and have been doing so for 20 years. However, I'm completely new to using Java to do so. In the past, I wrote games in BASIC, Blitz, and C++ using DirectX. Being familiar with C/C++, the Java language syntax is not a hurdle for me.
    I've never created a networking game, but I feel that if I tried to create one using one of the programming languages I already know that I would succeed at doing so. (I'm just trying to show that I feel confident in programming with the languages that i know)
    The dilemma here is that someone else would like me to program a turn'based multiplayer game for them in Java.
    I've downloaded the NetBeans 4.1 IDE and uncovered a lot of terms and such that I'm unfamiliar with.
    What I'm looking for from you guys is an overview of what I need to do to achieve my ultimate goal of creating this online game.
    As a reference, I need to create a game very similar to this one:
    http://www.tacticsarena.com/play/
    Click on the "Launch Game: Tactics Arena Online" link to see the game.
    Create a new account to play (accounts are free).
    Upon starting the NetBeans IDE, I found that I could create several different types of projects. I guess first of all, I need to know what kind of project is best suited to make this type of game.
    To name a few, I have to select from:
    Java Application
    Java Class Library (is this an Applet?)
    Web Application
    Enterprise Application
    EJB Module
    Then I guess I would like to know if any of the above projects would be used to make the clients interface or the server side software or both? Or do I need to use some other kind of software/programming language/etc. to create the server side? (As a side note, typically what kind of Operating system would the server be using? I ask because I may set one up myself for testing purposes.)
    Somewhere I came upon the term 'Servlet'. Is this some kind of Java server application? Do I need/want to be using this?
    As you can see, I'm very lost at where to begin. I'm not at all unfamiliar with programming. I'm just unfamiliar with Java.
    WolRon

    Hi WolRon
    I am in the process of learning Java myself and from what i have read, you have a long road ahead of you!
    To start this Project the following will be essential for you to know:
    Applets - if this is going to an online game
    Multiple Threads - for the Server side
    Swing - for the GUI on both sides
    AWT - help work with the user input (mouseListeners, buttonListeners, etc)
    And knowledge of a database.
    those are the most obvious things that you will need to understand.
    I strongly suggest buying a Java book from which you need to start at the beginning. Although the concept of OOP is the same through most languages Java has terms - as do all languages- that will be different from the other languages. Starting at the beginning will be beneficial to your Java coding future.
    Good luck.

  • How to refresh my GUI in connect 4 game

    Hi all,
    I write an application of a beginner level of connect 4. It has a problem: I cannot reset/refresh the screen after I find a winner or tie. I wonder if someone here can give me a hand.
    Thanks.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    public class Connect4GUI extends JFrame
         private final int WIN_WIDTH=500;
         private final int WIN_HEIGHT=500;
         private JFrame frame;
        private JPanel panel_Center;
         private JButton[][] buttonsBoard;
         private int [][] chess;
         private JPanel panel;
        private JButton startButton;
         private JButton rePlayButton;
         private JButton exitButton;
        private static  String player1Name;
         private static  String player2Name;
         private static final int player1_ID=1;
         private static final int player2_ID=2;
        private String input;
         private boolean gameOver=false;
         private boolean playAgain=false;
         private static int steps=0;
    /********************constructor**************************************************/
    public Connect4GUI()
         playerInfo();
         showFrame();
         JOptionPane.showMessageDialog(null,"Press Start to start the game.");
    public void playerInfo()
         player1Name=JOptionPane.showInputDialog("Player 1 please enter your name.");
         player2Name=JOptionPane.showInputDialog("Player 2 please enter your name.");
    public void showFrame()
         setTitle("Connect 4");
         setSize( WIN_WIDTH,WIN_HEIGHT);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setLayout(new BorderLayout());
         JPanel panel_North=new JPanel();//show player info
         panel_North.setLayout(new FlowLayout());
         JLabel labelPlayer_1= new JLabel("player 1 is "+player1Name);
         JLabel labelPlayer_2= new JLabel("player 2 is "+player2Name);
         panel_North.add(labelPlayer_1);
         panel_North.add(labelPlayer_2);
         JPanel panel_South=new JPanel();//add several button
         panel_South.setLayout(new FlowLayout());
        //create buttons
         startButton=new JButton("Start");
         rePlayButton=new JButton("Replay");
         exitButton=new JButton("Exit");
        //button listern
         startButton.addActionListener(new myStartButton());
         rePlayButton.addActionListener(new myrePlayButton());
         exitButton.addActionListener(new myexitButton());
        //add buttons to the panel
         panel_South.add(startButton);
         panel_South.add(rePlayButton);
         panel_South.add(exitButton);
         panel_Center=new JPanel();//show the board
        panel_Center.setLayout(new GridLayout(6,7,10,10));//6x7 chess board
         buttonsBoard=new JButton[6][7];
         chess=new int[6][7];
             for (int r=0; r<6;r++)
                   for (int c=0;c<7;c++)
                        buttonsBoard[r][c]=new JButton();
                        buttonsBoard[r][c].setBackground(Color.yellow);
                        panel_Center.add(buttonsBoard[r][c]);
                        buttonsBoard[r][c].addActionListener(new mybuttonsBoard());//add actionListener
                    chess[r][c]=0;
         }//end for
         //construct the frame
        add(panel_North,BorderLayout.NORTH);
        add(panel_South,BorderLayout.SOUTH);
        add(panel_Center,BorderLayout.CENTER);
           setVisible(true);
    }//end showFrame()
    public boolean hasAWinner()
       boolean hasAWinner=false;
      //win at row
      for (int r=0;r<6;r++)
            for(int c=0;(c+3)<7;c++)
                    if(chess[r][c]==chess[r][c+1]&&
                          chess[r][c]==chess[r][c+2]&&
                          chess[r][c]==chess[r][c+3]&&
                          chess[r][c]==1)
                             JOptionPane.showMessageDialog(null,player1Name+" is a winner.");
                             hasAWinner=true;
                             return hasAWinner;
                     else if(chess[r][c]==chess[r][c+1]&&
                                chess[r][c]==chess[r][c+2]&&
                                chess[r][c]==chess[r][c+3]&&
                                chess[r][c]==2)
                             JOptionPane.showMessageDialog(null,player2Name+ " is a winner.");
                             hasAWinner=true;
                             return hasAWinner;
    //win at column
    for (int r=0;(r+3)<6;r++)
            for(int c=0;c<7;c++)
                    if(chess[r][c]==chess[r+1][c]&&
                           chess[r][c]==chess[r+2][c]&&
                           chess[r][c]==chess[r+3][c]&&
                           chess[r][c]==1)
                             JOptionPane.showMessageDialog(null, player1Name+" is a winner.");
                             hasAWinner=true;
                             return hasAWinner;
                      else if(chess[r][c]==chess[r+1][c]&&
                                 chess[r][c]==chess[r+2][c]&&
                                 chess[r][c]==chess[r+3][c]&&
                                 chess[r][c]==2)
                             JOptionPane.showMessageDialog(null,player2Name+" is a winner.");
                            hasAWinner=true;
                             return hasAWinner;
    //win at upleft-to-downright direction
    for (int r=0;(r+3)<6;r++)
            for(int c=0;(c+3)<7;c++)
                    if(chess[r][c]==chess[r+1][c+1]&&
                           chess[r][c]==chess[r+2][c+2]&&
                           chess[r][c]==chess[r+3][c+3]&&
                           chess[r][c]==1)
                             JOptionPane.showMessageDialog(null, player1Name+" is a winner.");
                             hasAWinner=true;
                             return hasAWinner;
                      else if(chess[r][c]==chess[r+1][c+1]&&
                                 chess[r][c]==chess[r+2][c+2]&&
                                 chess[r][c]==chess[r+3][c+3]&&
                                 chess[r][c]==2)
                             JOptionPane.showMessageDialog(null,player2Name+" is a winner.");
                            hasAWinner=true;
                             return hasAWinner;
    //win at downleft-to-upright direction
    for (int r=5;(r-3)>=0;r--)
            for(int c=0;(c+3)<7;c++)
                    if(chess[r][c]==chess[r-1][c+1]&&
                           chess[r][c]==chess[r-2][c+2]&&
                           chess[r][c]==chess[r-3][c+3]&&
                           chess[r][c]==1)
                             JOptionPane.showMessageDialog(null, player1Name+" is a winner.");
                             hasAWinner=true;
                             return hasAWinner;
                      else if(chess[r][c]==chess[r-1][c+1]&&
                                 chess[r][c]==chess[r-2][c+2]&&
                                 chess[r][c]==chess[r-3][c+3]&&
                                 chess[r][c]==2)
                             JOptionPane.showMessageDialog(null,player2Name+" is a winner.");
                            hasAWinner=true;
                             return hasAWinner;
    return hasAWinner;
    }//end hasAwinner
    public boolean hasATie()
         boolean hasATie=false;
         if(steps==42 && hasAWinner()==false)
                     JOptionPane.showMessageDialog(null,"The game has a a tie.");
                    hasATie=true;
                     return hasATie;
            return hasATie;
    }//end hasATie
    /***********************listener class *******************************************/
    private class myStartButton implements ActionListener
         public void actionPerformed(ActionEvent e)
              //JOptionPane.showMessageDialog(null,"Now the game starts.");
              input=JOptionPane.showInputDialog(player1Name+" enter your name and make a move.");//start the game
    private class myrePlayButton implements ActionListener
         public void actionPerformed(ActionEvent e)
            if(steps>0)
                        ///how to clear the old frame???
                    JOptionPane.showMessageDialog(null,"new game starts.");
                       input=JOptionPane.showInputDialog(player1Name+" enter your name and make a move.");//start the game
                 else
                      JOptionPane.showMessageDialog(null,"You haven't started a new game yet.");
    }//end myrePlayButton
    private class myexitButton implements ActionListener
         public void actionPerformed(ActionEvent e)
                                                          ///how to cancel????????
                          JOptionPane.showMessageDialog(null,"Are you sure you want to stop the game?");
                          if(e.getActionCommand().equals("Exit"))
                              {System.exit(0);}
    }//end myexitButton
    private class mybuttonsBoard implements ActionListener
         public void actionPerformed(ActionEvent e)
           for (int r=0; r<6; r++)
                     for (int c=0; c<7;c++)
                        if(e.getSource()==buttonsBoard[r][c]
                            &&chess[r][c]==0
                            &&input.equals(player1Name))
                             buttonsBoard[r][c].setBackground(Color.red);
                                       chess[r][c]=player1_ID;
                                            steps++;
                                if(hasAWinner()==true||hasATie()==true)//has a winner or tie
                                             gameOver=true;
                                             repaint();
                                            break;
                               else
                                      input=JOptionPane.showInputDialog(player2Name+
                                          " enter your name and make a move.");
                      else if(e.getSource()==buttonsBoard[r][c]
                               &&chess[r][c]==0
                               &&input.equals(player2Name))
                                    buttonsBoard[r][c].setBackground(Color.black);
                                         chess[r][c]=player2_ID;
                                              steps++;
                                         if(hasAWinner()==true||hasATie()==true)//has a winner or tie
                                                 gameOver=true;
                                                      break;
                                       else
                                            input=JOptionPane.showInputDialog(player1Name+
                                                            " enter your name and make a move.");
              }//end for
        if(gameOver==true)
                      JOptionPane.showMessageDialog(null,"press Replay to"+
                                         " replay the game or press Exit to exit the game");//replay the game
    }//end actionPerformed
    }//end class
    public static void main(String []args)
              Connect4GUI b=new Connect4GUI();
         }//end main
    }//end Board

    The problem is solved.

  • How to move a button in gird layout(16-block game)?

    I am designing a 16-block puzzel game and don't have any idea about how to move buttons in a grid on mouse click.

    This is the code now me help me to solve this problem.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.util.*;
    public class Puzzel extends JFrame {
              JButton[] arr = new JButton[15];
              String[] add = {"1.jpg","2.jpg","3.jpg","4.jpg","5.jpg","6.jpg","7.jpg","8.jpg","9.jpg","10.jpg","11.jpg","12.jpg","13.jpg","14.jpg","15.jpg"};
              int X;
              int Y;
              public Puzzel(){
                        Image image;
                        Toolkit toolkit= Toolkit.getDefaultToolkit();
                        image=toolkit.getImage("icon.jpg");
                        ImageIcon icon=new ImageIcon("icon.jpg");
                        setIconImage(image);
                        setTitle("Puzzal");
                        JMenuItem pic = new JMenuItem("Solved");
                        pic.setMnemonic('a');
                        JPanel jp = new JPanel(new GridLayout(4,4));
                        ArrayList list = new ArrayList();
    MouseListenerClass M1 = new MouseListenerClass();
                           for(int x = 0; x < arr.length; x++)
                               arr[x] = new JButton(add[x], new ImageIcon(add[x]));
                               getContentPane().add(arr[x]);
                              list.add(arr[x]);
                        Collections.shuffle(list);
                        for(int x = 0; x < list.size(); x++)
                              jp.add((JButton)list.get(x));
                            getContentPane().add(jp);
                                 pack();
                                 setSize(427,427);
                                        setResizable(false);
                        /*for(int x=0;x<arr.length;x++){
                             arr[x].addSelectionListener(new SelectionAdapter());
                   public void widgetSelected(SelectionEvent event){System.out.println("IN");
                        if (event.getSource().getClass().equals(Button.class)){
                             Button button = (Button) event.getSource();
                             if (button.getText().equals("") )
                                  Toolkit.getDefaultToolkit().beep();
                                  else
                                       this.swapPlaces(((Integer) button.getData()).intValue());
                   public void widgetDefaultSelected(SelectionEvent event){
                                  System.out.println("Widget was defaultselected: " + event.getSource());
               for(int x = 0; x < arr.length; x++)
              arr[x].addMouseMotionListener(M1);
              private class MouseListenerClass extends MouseMotionAdapter
                   public void mouseDragged(MouseEvent E)
                   X=E.getX();
                   Y=E.getY();
                   for(int x = 0; x < arr.length; x++)
                        arr[x].setBounds(X,Y,100,100);
    public static void main(String[] args){
                    new Puzzel().setVisible(true);}
         }

  • Problem with Double Buffering and Swing

    Hi
    I made a game and basically it works pretty well, my only problem is it flickers really badly right now. I read up on a whole lot of forums about double buffering and none of those methods seemed to work. Then I noticed that Swing has double buffering built in so I tried that but then I get compilation errors and I'm really not sure why. My original code was a console application and worked perfectly, then I ported it into a JApplet and it still works but it flickers and thats what I'm tryign to fix now.
    The code below is in my main class under the constructor.
    Heres the double buffering code I'm trying to use, I'm sure you all seen it before lol
    public void update(Graphics g)
              // initialize buffer
              if (dbImage == null)
                   dbImage = createImage(this.getSize().width, this.getSize().height);
                   dbg = dbImage.getGraphics();
              // clear screen in background
              dbg.setColor(getBackground());
              dbg.fillRect(0, 0, this.getSize().width, this.getSize().height);
              // draw elements in background
              dbg.setColor(getForeground());
              paint(dbg);
              // draw image on the screen
              g.drawImage(dbImage, 0, 0, this);
         }My paint is right under neath and heres how it looks
    This snipet of code works but when I change the method to
    public paintComponent(Graphics g){
    super.paintComponent(g)...
    everythign stops working and get a compilation error and says that it can't find paintComponent in javax.swing.JFrame.
    public void paint(Graphics g)
              super.paint(g);
              //if game starting display menue
              if (show_menue)
                   //to restart lives if player dies
                   lives = 3;
                   menue.draw_menue(g);
                   menue_ufo1.draw_shape(g);
                   menue_ufo2.shape_color = Color.DARK_GRAY;
                   menue_ufo2.draw_shape(g);
                   menue_ufo3.shape_color = Color.BLUE;
                   menue_ufo3.draw_shape(g);
                   menue_ufo4.shape_color = new Color(82, 157, 22);
                   menue_ufo4.draw_shape(g);
                   menue_ufo5.draw_shape(g);
                   menue_ufo6.shape_color = new Color(130, 3, 3); ;
                   menue_ufo6.draw_shape(g);
                   menue_turret.draw_ship(g);
                   menue_ammo.draw_ammo(g);
              else
                   //otherwise redraw game objects
                   gunner.draw_ship(g);
                   y_ammo.draw_ammo(g);
                   grass.draw_bar(g);
                   o_ufo.draw_shape(g);
                   b_ufo.draw_shape(g);
                   m_ufo.draw_shape(g);
                   s_ufo.draw_shape(g);
                   z_ufo.draw_shape(g);
                   xx_ufo.draw_shape(g);
                   info.draw_bar(g);
                   live_painter.draw_lives(g, lives);
                   score_painter.draw_score(g, score);
                   level_display.draw_level(g, level);
                   explosion.draw_boom(g);
         }I just want to get rid of the flickering for now so any help will be greatly appreciated. Depending which will be simpler I can either try to double buffer this program or port it all to swing but I'm not sure which elements are effected by AWT and which by Swing. Also I read some of the Java documentation but couldn't really understand how to implement it to fix my program.
    Thanks in advance
    Sebastian

    This is a simple animation example quickly thrown together. I have two classes, an animation panel which is a JPanel subclass that overrides paintComponent and draws the animation, and a JApplet subclass that simply holds the animation panel in the applet's contentpane:
    SimpleAnimationPanel.java
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    import javax.swing.Timer;
    class SimpleAnimationPanel extends JPanel
        private static final int DELAY = 20;
        public static final int X_TRANSLATION = 2;
        public static final int Y_TRANSLATION = 2;
        private Point point = new Point(5, 32);
        private BufferedImage duke = null;
        private Timer timer = new Timer(DELAY, new TimerAction());
        public SimpleAnimationPanel()
            try
                // borrow an image from sun.com
                duke = ImageIO.read(new URL(
                        "http://java.sun.com/products/plugin/images/duke.wave.med.gif"));
            catch (MalformedURLException e)
                e.printStackTrace();
            catch (IOException e)
                e.printStackTrace();
            setPreferredSize(new Dimension(600, 400));
            timer.start();
        // do our drawing here in the paintComponent override
        @Override
        protected void paintComponent(Graphics g)
            super.paintComponent(g);
            if (duke != null)
                g.drawImage(duke, point.x, point.y, this);
        private class TimerAction implements ActionListener
            @Override
            public void actionPerformed(ActionEvent e)
                int x = point.x;
                int y = point.y;
                Dimension size = SimpleAnimationPanel.this.getSize();
                if (x > size.width)
                    x = 0;
                else
                    x += X_TRANSLATION;
                if (y > size.height)
                    y = 0;
                else
                    y += Y_TRANSLATION;
                point.setLocation(new Point(x, y)); // update the point
                SimpleAnimationPanel.this.repaint();
    }AnimationApplet.java
    import java.lang.reflect.InvocationTargetException;
    import javax.swing.JApplet;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    public class AnimationApplet extends JApplet
        public void init()
            try
                SwingUtilities.invokeAndWait(new Runnable()
                    public void run()
                        // construct the panel
                        JPanel simpleAnimation = new SimpleAnimationPanel();
                        // put it in the contentPane of the JApplet
                        getContentPane().add(simpleAnimation);
                        setSize(simpleAnimation.getPreferredSize());
            catch (InterruptedException e)
                e.printStackTrace();
            catch (InvocationTargetException e)
                e.printStackTrace();
    }Here's a 3rd bonus class that shows how to put the JPanel into a stand-alone program, a JFrame. It's very similar to doing it in the JApplet:
    AnimationFrame.java
    import javax.swing.JFrame;
    public class AnimationFrame
        private static void createAndShowUI()
            JFrame frame = new JFrame("SimpleAnimationPanel");
            frame.getContentPane().add(new SimpleAnimationPanel());
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        public static void main(String[] args)
            java.awt.EventQueue.invokeLater(new Runnable()
                public void run()
                    createAndShowUI();
    }Edited by: Encephalopathic on Mar 15, 2008 11:01 PM

Maybe you are looking for

  • E61i hangs when receiving email

    Hi all, I've got my great nokia E61i for a couple of weeks now, but I am experiencing something weird when receiving my emails (POP). When receiving my emails, I see the first email (header) coming in, but that's it. The meter stops moving and I can

  • TV Shows menu

    I just got a new video iPod today for my birthday and I synced with iTunes - but when I go to video to watch tv shows that I have synced, the tv shows option is not even on the menu.....help!! Thanks!

  • Lightspark PKGBUILD: problems on building

    I was creating a new PKGBUILD for lightsmark-git, an alternative opensource flash plugin: # Contributor: Flamelab <[email protected]> pkgname=lightspark-git _realpkgname=lightspark pkgver=20100518 pkgrel=1 pkgdesc="An alternative Flash Player impl

  • IPhoto - Album organization

    Hello! I currently have about 30 folders inside the Album section of my iPhoto that I would like to alphabetize so there's some organization.  I haven't been able to find anything of any use online.  Does anyone know how to rearrange the folders so t

  • I want to change my secure adress, because i lost the answers for the security question

    APP STORE, I want to change my secure adress, because i lost the answers for the security question. Because my old mail secure adress was closed.