Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 11 of 11

Thread: Need Help Please and Thank You

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Need Help Please and Thank You

    I am trying to create a ConnectFour game using GUI. I created a simple interface and put a picture of the board game on there, but I am not sure how to make the game actually work using the mouse listener. I want have pictures of two different color tokens that I want to be the game pieces, but I am not sure how to make them go to the correct location when the user clicks on the game. It is a multiplayer game. Thanks. Here is the code, and a picture of the output is also attached:

    <// Import the proper package for the program
    import java.util.*;
    import javax.swing.JApplet;
    import javax.swing.JFrame;
     
    public class ConnectFour extends JApplet
    {
    	// Create instance variables
    	private int APPLET_WIDTH = 900, APPLET_HEIGHT = 750;
    	private ConnectFourPanel connectFourPanel;
    	private JFrame frame;
     
    	// The method init initializes the Applet with a Pane with two tabs
    	public void init()
    	{
    		 // Initialize the frame to the title of the game
    		 frame = new JFrame("Connect 4");
     
    	     // Register the panel
    	     connectFourPanel = new ConnectFourPanel();
     
    	     // Set the content pane, set the size of the Applet, set it to exit when closed,
    	     // set it to visible, and set it to be not resizable
    	     frame.setContentPane(connectFourPanel);
    	     frame.setSize (APPLET_WIDTH, APPLET_HEIGHT);
    	     frame.setVisible(true);
    	     frame.setResizable(true);
    	 } // Ends the init method
    } // Ends the Connect4 class
    >
    *



    <//Import the proper packages
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.border.LineBorder;
     
    public class ConnectFourPanel extends JPanel
    {
    	// Create instance variables
    	private JLabel[][] gameBoardArrayLabel;
    	private JButton newButton, exitButton;
    	private JLabel PlayerOneLabel, PlayerTwoLabel, drawLabel, gameBoardLabel;
    	private JPanel informationPanel, gameBoardPanel, buttonPanel, smallerPanel1, smallerPanel2;
    	private final int MAX_ROWS, MAX_COLUMNS;
    	private int playerOneCount, playerTwoCount, draw;
     
    	// Create the graphics variables
    	public BufferedImage gameBoardImage;
    	public BufferedImage playerOneImage;
    	public Image PlayerTwoImage;
    	public ImageIcon gameBoardIcon;
    	public ImageIcon playerOneIcon;
    	public ImageIcon playerTwoIcon;
     
    	// Create a constructor
    	public ConnectFourPanel()
    	{
    		// Initialize the maximum amount of rows and columns for the board
    		MAX_ROWS = 7;
    		MAX_COLUMNS = 6;
     
    		// Initialize the number of wins and draws to zero
    		playerOneCount = 0;
    		playerTwoCount = 0;
    		draw = 0;
     
    		// Create an object to play the game
    //		PlayConnectFour() play = new PlayConnectFour();
     
    		// Initialize the gameBoardArrayLabel size
    	    gameBoardArrayLabel = new JLabel[MAX_ROWS][MAX_COLUMNS];
     
    	    // Set the graphics for the game board and the tokens of the players
    	    gameBoardIcon = new ImageIcon("Connect4Board.jpg");
    	    playerOneIcon = new ImageIcon("BlueToken.jpg");
    	    playerTwoIcon = new ImageIcon("PurpleToken.jpg");
     
    	    // Get the Images from the icons
    //	    gameBoardImage = gameBoardIcon.getImage();
    //	    playerOneImage = playerOneIcon.getImage();
    //	    PlayerTwoImage = playerTwoIcon.getImage();
     
    		// Try to read the game board image onto the screen
    	    try
    	    {
    	    	gameBoardImage = ImageIO.read(new File("Connect4Board.jpg"));
    	    }
     
    		// Catch the IOException if the image does not display
    	    catch (IOException exception)
    	    {
    	    	System.out.println("The picture of the game board could not be read; this is an IOException.");
    	    }
     
    // Try to read the player one image onto the screen
    	    try
    	    {
    	    	playerOneImage = ImageIO.read(new File("BlueToken.jpg"));
    	    }
     
    		// Catch the IOException if the image does not display
    	    catch (IOException exception)
    	    {
    	    	System.out.println("The picture of the blue token could not be read; this is an IOException.");
    	    }
     
    	    // Initialize the two dimensional array, center it, and create a border for the grid
    	    for (int row = 0; row < MAX_ROWS; row++)
    	    {
    	        for (int column = 0; column < MAX_COLUMNS; column++)
    	        {
    	        	gameBoardArrayLabel[row][column] = new JLabel("0");
     
    	        	gameBoardArrayLabel[row][column].setHorizontalAlignment(SwingConstants.CENTER);
    	        	gameBoardArrayLabel[row][column].setBorder(BorderFactory.createLineBorder(Color.BLACK));
    	        }
    	    }
     
    		// Create a layout for the Connect4Panel
    		// this.setLayout(new GridLayout(3, 1));
    		this.setLayout(new BorderLayout());
     
    		// Create a panel to talk to the players and set the layout
    		informationPanel = new JPanel();
    		informationPanel.setLayout(new GridLayout(1, 1));
     
    		// Add the informationPanel to the Connect4Panel
    		add(informationPanel);
     
    		// Create a label that tells the user how many time player 1 won and adds
    		// it to the informationPanel
    		PlayerOneLabel = new JLabel("Player 1 Total Wins: " + playerOneCount);
    		informationPanel.add(PlayerOneLabel);
     
    		// Create a label that tells the user how many time player 2 won and adds
    		// it to the informationPanel
    		PlayerTwoLabel = new JLabel("Player 2 Total Wins: " + playerTwoCount);
    		informationPanel.add(PlayerTwoLabel);
     
    		// Create a label that tells the user how many time player 2 won and adds
    		// it to the informationPanel
    		drawLabel = new JLabel("Total Draws: " + draw);
    		informationPanel.add(drawLabel);
     
    		// Set the size of the informationPanel and add it to the north
    		informationPanel.setPreferredSize(new Dimension(50, 50));
    		add (informationPanel, BorderLayout.NORTH);
     
    		// Create a panel for the game board and set the layout
    		gameBoardPanel = new JPanel();
    		gameBoardPanel.setLayout(new GridLayout(1, 1));
     
    		// Add the gameBoardPanel to the connect4Panel
    		//gameBoardPanel.add(gameBoardImage);
     
    		// Add the image of the gameboard to the gameBoardLabel
    	    gameBoardLabel = new JLabel(new ImageIcon(gameBoardImage));
     
    		// Add the gameBoardLabel to the GameBoardPanel and set the size
    	    gameBoardPanel.add(gameBoardLabel);
    		gameBoardPanel.setPreferredSize(new Dimension(200, 600));
     
    		// Add the gameBoardPanel to the ConnectFourPanel and add it to the south
    		add(gameBoardPanel);
    		add (gameBoardPanel, BorderLayout.SOUTH);
     
    		// Add the each row and column of the gameBoardArrayLabel to the gameBoardPanel
    	    for (int row = 0; row < MAX_ROWS; row++)
    	    {
    	        for (int column = 0; column < MAX_COLUMNS; column++)
    	        {
    	        	//gameBoardPanel.add(gameBoardArrayLabel[row][column]);
    	        }
    	    }
     
    		// Create a PointListener object to listen to when the players press the mouse button
    		// on the gameBoardPanel and adds it to the canvas
    		PointListener listener2 = new PointListener();
    		gameBoardPanel.addMouseListener(listener2);
    		gameBoardPanel.addMouseMotionListener(listener2);
     
    		// Add the Mouse listener to each of the rows and columns in the array
    	    for (int row = 0; row < MAX_ROWS; row++)
    	    {
    	        for (int column = 0; column < MAX_COLUMNS; column++)
    	        {
    	        	gameBoardArrayLabel[row][column].addMouseListener(listener2);
    	        	gameBoardArrayLabel[row][column].addMouseMotionListener(listener2);
    	        }
    	    }
     
    		// Create the button panel and set the layout
    		buttonPanel = new JPanel();
    		buttonPanel.setLayout(new GridLayout(1, 2));
     
    		// Add the buttonPanel to the Connect4Panel
    		add(buttonPanel);
     
    		// Create a button that says "New Game" and add it to the buttonPanel
    		newButton = new JButton("New Game");
     
    		// Create a smallerPanel1 and add the newButton to minimize the newButton
    		smallerPanel1 = new JPanel();
    		smallerPanel1.add(newButton);
     
    		// Add the smallerPanel1 to the buttonPanel
    		buttonPanel.add(smallerPanel1);
     
    		// Create a button that says "Exit Game" and add it to the buttonPanel
    		exitButton = new JButton("Exit Game");
    		buttonPanel.add(exitButton);
     
    		// Create a smallerPanel2 and add exitButton to minimize the exitButton
    		smallerPanel2 = new JPanel();
    		smallerPanel2.add(exitButton);
     
    		// Add the smallerPanel2 to the buttonPanel
    		buttonPanel.add(smallerPanel2);
     
    		// Add the buttonPanel to the center
    		add (buttonPanel, BorderLayout.CENTER);
     
    		// Create a ButtonListener object to listen to when the user
    		// clicks the button and adds it
    	    ButtonListener listener = new ButtonListener();
    		newButton.addActionListener(listener);
     
    		// Adds the exitButton to the ButtonListener object
    		exitButton.addActionListener(listener);
    	} // End the ConnectFourPanel constructor
     
    	// This method needs to be defined to draw in this panel
        private class Canvas extends JPanel
        {
        	// Method that draws rectangles with their selected color, coordinate, and size.
        	public void paintComponent(Graphics page)
            {
        		// Calls the paintComponent method from the parent class
        		super.paintComponent(page);
     
    			page.setColor(Color.black);
        		// Sets the background color to white
        		//setBackground(Color.white);
     
        		// Draw the lines of the grid
    //   		page.drawLine(arg0, arg1, arg2, arg3);
     
        		int x =100;
        		int y = 150;
     
        		page.drawImage(gameBoardImage, x, y, null);
     
        		page.drawImage(playerOneImage, x, y, null);
     
        		gameBoardIcon.paintIcon(this, page, x, y);
        		playerOneIcon.paintIcon(this, page, x, y);
        		playerTwoIcon.paintIcon(this, page, x, y);
            }
        }
     
    	// Represents an action listener for the pet input field
    	private class ButtonListener implements ActionListener
    	{
    		public void actionPerformed(ActionEvent event)
    		{
     
    		}
    	} // Ends the ButtonListener class
     
    	// Represents a MouseListener and a MouseMotionListener that listens to the mouse when the user
        // plays Connect4
        private class PointListener implements MouseListener, MouseMotionListener
         {
        	//
            public void mouseClicked(MouseEvent event)
            {
            	for (int row = 0; row < MAX_ROWS; row++)
        	    {
        	        for (int column = 0; column < MAX_COLUMNS; column++)
        	        {
     //   	        	event.getComponent().compareTo();
        	        }
        	    }
            } // Ends the mouseClicked method
     
            // Additional methods in the MouseListener that are left blank
            public void mousePressed(MouseEvent event) {}
            public void mouseReleased(MouseEvent event) {}
            public void mouseEntered(MouseEvent event) {}
            public void mouseExited(MouseEvent event) {}
            public void mouseMoved(MouseEvent event) {}
            public void mouseDragged(MouseEvent event) {}
         } // End of PointListener
    } // Ends the Connect4Panel class>
    *



    <// Import the proper packages
    import javax.swing.JPanel;
     
    public class PlayConnectFour
    {
    	// Create instance variables
    	private int[][] gameBoard = new int[7][6];
    	private boolean player1;
    	private boolean player2;
     
    	// Create a constructor that sets the first player to player1
    	public PlayConnectFour()
    	{
    		player1 = true;
    		player2 = false;
    	}
     
    	public boolean takeTurns()
    	{
    		// Create local variable
    		boolean currentPlayer = player1;
     
    //		while(player1.winner() == false)
    		{
    			if (player1 = true)
    			{
    				player1 = false;
    				player2 = true;
    				currentPlayer = player2;
    			}
     
    			else
    			{
    				player1 = true;
    				player2 = false;
    				currentPlayer = player1;
    			}
    		}
     
    		// Return whose turn it is
    		return currentPlayer;
    	}
     
    	//
    /*	public void setTokens(int column, int row)
    	{
    	    if (player1 == true)
    	    {
    	      gameBoard[row][column].setIcon(new ImageIcon("");
    	    }
     
    	    else
    	    {
    	    	gameBoard[row][column].setIcon(new ImageIcon("");
    	    }
    */
    	// Method that keeps track of who won the game
    	public boolean setWinner()
    	{
    		// Create a local variable
    		boolean winner = false;
     
    		// Check for a horizontal win
     
    		// Check for a verticle win
     
    		// Check for a diagnol win
    		return true;
    	}
    }>
    *
    Attached Images Attached Images
    Last edited by jmoore; April 15th, 2012 at 12:12 PM.

  2. #2
    Junior Member
    Join Date
    Apr 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need Help Please and Thank You

    Can anyone give me some ideas on how I can go about doing this or if it is even possible using the BufferedImage? Please and thank you.

  3. #3
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need Help Please and Thank You

    Please Edit your post and wrap your code with[code=java]<YOUR CODE HERE>[/code] to get highlighting. The unformatted code is hard to read and work with.
    If you don't understand my answer, don't ignore it, ask a question.

  4. #4
    Junior Member
    Join Date
    Apr 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need Help Please and Thank You

    Thanks! I edited it, and not it looks like it does in Eclipse now.

    Alright. Can anyone give me some ideas on how I can go about doing this or if it is even possible using the BufferedImage? Please and thank you

  5. #5
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need Help Please and Thank You

    What is supposed to happen? I get the applet and I get a frame with an image in the center. Then what?

    Have you looked at the tutorial for mouse listeners?
    http://docs.oracle.com/javase/tutori...elistener.html
    Last edited by Norm; April 15th, 2012 at 01:01 PM.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #6
    Junior Member
    Join Date
    Apr 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need Help Please and Thank You

    Well, Iwould like to have a token fall to the bottom of the board when a certain column is clicked, but I am not sure how to make the board listen. Is this possible with a BufferedImage? If so, how can I make it listen. I understand that I need the X and Y positions for the places on the board, but I am not sure how to find those either...

  7. #7
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need Help Please and Thank You

    Listen for what?

    Have you looked at the tutorial for mouse listeners?
    How to Write a Mouse Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)

    What do you want to do with a BufferedImage?
    If you don't understand my answer, don't ignore it, ask a question.

  8. #8
    Junior Member
    Join Date
    Apr 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need Help Please and Thank You

    The buffered image was just used to show the game board for the user to see. This board should listen to when the user clicks on parts of the game board. For instance, if the user clicks on the top left corner, the token should fall to the bottom of that first column as long as there is not another token already there. If there is a token already there, then it should go onto the space above where that token is.

    Yes, I have looked at the link. I guess, I am mainly just confused by the two dimensional array, and how to implement it in regards to the game board picture. When I was writing the paintComponent method, it doesn't really draw the playerOneImage (ie the token for player one over the board) Or maybe if it is easier to just use the paintComponent method using the drawOval method to draw circles over parts of the game board. I can't figure out how to make any of the tokens show when the user clicks on the token. I have tried just trying to get the picture of the token to show over the gameboard to figure out the coordinates for where to put the game pieces, but the image does not even show on the screen...

  9. #9
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need Help Please and Thank You

    Is a token an image? Have you tried using the drawImage() method in paintComponent()?

    Where do you create an instance of your Canvas class?

    BTW Canvas is the name of a Java SE class. Pick another name to avoid confusion.
    Last edited by Norm; April 15th, 2012 at 01:29 PM.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #10
    Junior Member
    Join Date
    Apr 2012
    Posts
    7
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Need Help Please and Thank You

    Yes. In the paintComponent method, I have:
    <page.drawImage(gameBoardImage, x, y, null);
        		page.drawImage(playerOneImage, x, y, null);>

    The first line makes the game board appear on the screen so I tried the same method for the token, which is also an image.

    Hmmm...I guess I don't have an instance of the canvas class in my program...Should I put it in the constructor?
    Last edited by jmoore; April 15th, 2012 at 02:09 PM.

  11. #11
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Need Help Please and Thank You

    You need to check out the contents of the GUI and how you are laying it out and where you want what to be shown. Where is the Canvas class used? (rename it to MyCanvas)
    If you don't understand my answer, don't ignore it, ask a question.