Results 1 to 12 of 12
  1. #1
    yemista is offline Member
    Join Date
    Oct 2011
    Posts
    41
    Rep Power
    0

    Default making a chess board gui

    hi, I am new to gui with java and i am having trouble making a GUI that represents a chess board. I can get a grid just fine, but when it comes to the event handler, I am having trouble. I want it to work so that when you click on one square, the contents are stored in the event handler, and then when you click on another square, the content moves to that square. currently, all that happens is that when i double click a white square, it turns green! here is all my source code for this project

    Java Code:
    file1
    import java.awt.*;
    import javax.swing.*;
    
    public class SquarePanel extends JPanel {
    	String content;
    	
    	public SquarePanel() {
    		content = "";
    	}
    	
    	public void paintComponent(Graphics g) {
    		int width = getWidth();
    		int height = getHeight();
    		g.setColor(Color.black);
    		g.fillRect(0, 0, width, height);
    	}
    
    	public String getContent() {
    		return content;
    	}
    	
    	public void setContent(String c) {
    		content = c;
    	}
    }
    
    
    file2
    import java.awt.*;
    import javax.swing.*;
    
    public class WhiteSquarePanel extends SquarePanel {
    
    	public WhiteSquarePanel() {
    		super();
    	}
    	
    	public void paintComponent(Graphics g) {
    		int width = getWidth();
    		int height = getHeight();
    		g.setColor(Color.black);
    		g.drawRect(0, 0, width, height);
    	}
    	
    	public void paint(Graphics g) {
    		paintComponent(g);
    	}
    }
    
    file3
    import java.awt.*;
    import javax.swing.*;
    
    public class BlackSquarePanel extends SquarePanel {
    
    	public BlackSquarePanel() {
    		super();
    	}
    	
    	public void paintComponent(Graphics g) {
    		int width = getWidth();
    		int height = getHeight();
    		g.setColor(Color.green);
    		g.fillRect(0, 0, width, height);
    	}
    	
    	public void paint(Graphics g) {
    		paintComponent(g);
    	}
    }
    
    file4
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class MoveListener implements MouseListener {
    	private int first_click;
    	private SquarePanel first_source;
    	
    	public MoveListener() {
    		first_click = 0;
    	}
    	
    	
    	/* Empty method definition. */
        public void mousePressed(MouseEvent e) {
        }
    
        /* Empty method definition. */
        public void mouseReleased(MouseEvent e) {
        }
    
        /* Empty method definition. */
        public void mouseEntered(MouseEvent e) {
        }
    
        /* Empty method definition. */
        public void mouseExited(MouseEvent e) {
        }
    
        public void mouseClicked(MouseEvent e) {
            SquarePanel p = (SquarePanel)e.getSource();
    		String content = null;
    		
    		if(first_click == 0) {
    			first_source = p;
    			++first_click;
    		}
    		else {
    			first_click = 0;
    			content = first_source.getContent();
    			first_source.repaint();
    			p.repaint();
    			p.setContent(content);
    			p.getGraphics().drawString(content,p.getWidth()/2,p.getHeight());
    		}
    		
    		System.out.println(content);
    		System.out.println(first_click);
        }
    
    }
    
    file 5
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
    public class GameFrame extends JFrame {
    		
    	public GameFrame() {
    		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		Container con = this.getContentPane();
    		setSize(900,900);
    		setLocation(0,0);
    		con.setLayout(new GridLayout(4,4));
    		JPanel pane1 = new WhiteSquarePanel();
    		JPanel pane2 = new BlackSquarePanel();
    		JPanel pane3 = new WhiteSquarePanel();
    		JPanel pane4 = new BlackSquarePanel();
    		JPanel pane5 = new WhiteSquarePanel();
    		JPanel pane6 = new BlackSquarePanel();
    		JPanel pane7 = new WhiteSquarePanel();
    		JPanel pane8 = new BlackSquarePanel();
    		JPanel pane9 = new WhiteSquarePanel();
    		JPanel pane10 = new BlackSquarePanel();
    		JPanel pane11 = new WhiteSquarePanel();
    		JPanel pane12 = new BlackSquarePanel();
    		JPanel pane13 = new WhiteSquarePanel();
    		JPanel pane14 = new BlackSquarePanel();
    		JPanel pane15 = new WhiteSquarePanel();
    		JPanel pane16 = new BlackSquarePanel();
    		MouseListener listener = new MoveListener();
    		((SquarePanel)pane1).setContent("Hellow World!");
    		pane1.addMouseListener(listener);
    		pane2.addMouseListener(listener);
    		pane3.addMouseListener(listener);
    		pane4.addMouseListener(listener);
    		pane5.addMouseListener(listener);
    		pane6.addMouseListener(listener);
    		pane7.addMouseListener(listener);
    		pane8.addMouseListener(listener);
    		pane9.addMouseListener(listener);
    		pane10.addMouseListener(listener);
    		pane11.addMouseListener(listener);
    		pane12.addMouseListener(listener);
    		pane13.addMouseListener(listener);
    		pane14.addMouseListener(listener);
    		pane15.addMouseListener(listener);
    		pane16.addMouseListener(listener);
    		
    		con.add(pane1);
    		con.add(pane2);
    		con.add(pane3);
    		con.add(pane4);
    		con.add(pane6);
    		con.add(pane5);
    		con.add(pane8);
    		con.add(pane7);
    		con.add(pane9);
    		con.add(pane10);
    		con.add(pane11);
    		con.add(pane12);
    		con.add(pane14);
    		con.add(pane13);
    		con.add(pane16);
    		con.add(pane15);
    
    		setVisible(true);
    		
    		pane1.getGraphics().setColor(Color.black);
    		pane1.getGraphics().drawString("Hello World!",pane1.getWidth()/2,pane1.getHeight()/2);
    	}
    	
    	public static void main(String[] args) {
    		new GameFrame();
    	}
    
    }
    Last edited by Fubarable; 10-11-2011 at 08:33 PM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: making a chess board gui

    First off, I took the liberty of fixing your end code tag so that it used a backslash, /, rather than a forward slash, \.

    Some comments on your code, noted by //!!:

    Java Code:
    //!! Black and White Square panels should be one class, SquarePanel will do, 
    //!! whose appearance differs based on a parameter(s) passed into the constructor
    class WhiteSquarePanel extends SquarePanel {
    
       public WhiteSquarePanel() {
          super();
       }
    
       public void paintComponent(Graphics g) {
          int width = getWidth();
          int height = getHeight();
    
          //!! easier to simply use a LineBorder in constructor:
          g.setColor(Color.black);
          g.drawRect(0, 0, width, height);  
       }
    
       public void paint(Graphics g) {
          paintComponent(g);
       }
    }
    
    class BlackSquarePanel extends SquarePanel {
    
       public BlackSquarePanel() {
          super();
       }
    
       
       public void paintComponent(Graphics g) {
          int width = getWidth();
          int height = getHeight();
          g.setColor(Color.green);
          g.fillRect(0, 0, width, height);
       }
    
       //!! WTF?? What the heck are you trying to do here??
       public void paint(Graphics g) {
          paintComponent(g);
       }
    }
    
    class MoveListener implements MouseListener {
       private int first_click;
       private SquarePanel first_source;
    
       public MoveListener() {
          first_click = 0;
       }
    
       //....
    
       //!! you want to use mousePressed, not mouseClicked
       public void mouseClicked(MouseEvent e) {
          SquarePanel p = (SquarePanel) e.getSource();
          String content = null;
    
          if (first_click == 0) {
             first_source = p;
             ++first_click;
          } else {
             first_click = 0;
             content = first_source.getContent();
             first_source.repaint();
    
             //!! you'll want to reverse the order these two, I think
             p.repaint();
             p.setContent(content);
             
             //!! no, don't use getGraphics as the Graphics object
             //!! will not be stable:
             p.getGraphics().drawString(content, p.getWidth() / 2, p.getHeight());
          }
    
          System.out.println(content);
          System.out.println(first_click);
       }
    
    }
    
    public class GameFrame extends JFrame {
    
       public GameFrame() {
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          Container con = this.getContentPane();
          setSize(900, 900);
          setLocation(0, 0);
          con.setLayout(new GridLayout(4, 4));
          
          //!! If ever I saw a need for an array and a for loop it is here:
          JPanel pane1 = new WhiteSquarePanel();
          JPanel pane2 = new BlackSquarePanel();
    
          //...
    
          setVisible(true);
    
          //!! again, never ever use getGraphics on a Swing component.
          pane1.getGraphics().setColor(Color.black);
          pane1.getGraphics().drawString("Hello World!", pane1.getWidth() / 2,
                pane1.getHeight() / 2);
       }
    
       public static void main(String[] args) {
          new GameFrame();
       }
    
    }

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: making a chess board gui

    Some more suggestions...

    If this were my application, I'd consider ...:
    • Creating a single Square class that displays white or black depending on the square's location in the grid.
    • passing the Square's rank and file into its constructor and use this information to decide if it should display itself as white or black (using whatever Color's you choose for this).
    • One easy way to decide this is to check rank % 2 vs file % 2.
    • giving the Square JPanels a GridBagLayout since this will centralize any single component added to the JPanel.
    • placing JLabels that held ImageIcons on the JPanel for my playing pieces.
    • giving my Square classes an easy way to place, remove, or obtain its current playing piece.
    • setting my Square's background color in its constructor via the setBackground(Color c) method.
    • creating my Squares in two nested for loops.
    • revalidating and repainting any Square after content has been removed or added.

  4. #4
    yemista is offline Member
    Join Date
    Oct 2011
    Posts
    41
    Rep Power
    0

    Default Re: making a chess board gui

    ok, I made the changes. Here are the new bugs that I cant seem to fix. The first one is, even though I have 2 for loops each iterating 4 times, only 12 squares show up!. The second weird bug, is I can get the text to move around ok, but it wont dissappear from the white squares, only from the green. Code is the same for both so I dont see why this is happening. Also, I tried to make SquarePanel one class with a constructor of SquarePanel(Color c), but the squares ended up having no color. I passed it parameters of Color.black and Color.white, but thats really a minor problem

    Java Code:
    file 1
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
    public class GameFrame extends JFrame {
    		
    	public GameFrame() {
    		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		Container con = this.getContentPane();
    		setSize(900,900);
    		setLocation(0,0);
    		con.setLayout(new GridLayout(4,4));
    		JPanel pane = null;
    		JPanel lastpanel = new WhiteSquarePanel();
    		MouseListener listener = new MoveListener();
    		
    		for(int i = 0; i < 4; ++i) {
    			for(int j = 0; j < 4; ++j) {
    				pane = lastpanel;
    				
    				if(j != 0) {
    					if(pane instanceof WhiteSquarePanel)
    						lastpanel = new BlackSquarePanel();
    					else
    						lastpanel = new WhiteSquarePanel();
    				}
    				
    				pane.addMouseListener(listener);
    				con.add(pane);
    			}
    		}
    
    		setVisible(true);
    		
    		((SquarePanel)pane).setContent("Hello World!");
    		pane.repaint();
    	}
    	
    	public static void main(String[] args) {
    		new GameFrame();
    	}
    
    }
    
    file2
    import java.awt.*;
    import javax.swing.*;
    
    public class BlackSquarePanel extends SquarePanel {
    
    	public BlackSquarePanel() {
    		super();
    	}
    	
    	public void paintComponent(Graphics g) {
    		int width = getWidth();
    		int height = getHeight();
    		g.setColor(Color.green);
    		g.fillRect(0, 0, width, height);
    		g.setColor(Color.black);
    		g.drawString(content,getWidth()/2,getHeight()/2);
    	}
    	
    }
    
    file3
    import java.awt.*;
    import javax.swing.*;
    
    public class WhiteSquarePanel extends SquarePanel {
    
    	public WhiteSquarePanel() {
    		super();
    	}
    	
    	public void paintComponent(Graphics g) {
    		int width = getWidth();
    		int height = getHeight();
    		g.setColor(Color.black);
    		g.drawRect(0, 0, width, height);
    		g.drawString(content,getWidth()/2,getHeight()/2);
    	}
    	
    }
    
    file4
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class MoveListener implements MouseListener {
    	private int first_click;
    	private SquarePanel first_source;
    	
    	public MoveListener() {
    		first_click = 0;
    	}
    	
    	
    	
        public void mousePressed(MouseEvent e) {
    		SquarePanel p = (SquarePanel)e.getSource();
    		String content = null;
    		
    		if(first_click == 0) {
    			first_source = p;
    			++first_click;
    		}
    		else {
    			first_click = 0;
    			content = first_source.getContent();
    			first_source.setContent("");
    			first_source.repaint();
    			p.setContent(content);
    			p.repaint();
    			
    		}
    		
    		System.out.println(content);
    		System.out.println(first_click);
    	}
    
        /* Empty method definition. */
        public void mouseReleased(MouseEvent e) {
        }
    
        /* Empty method definition. */
        public void mouseEntered(MouseEvent e) {
        }
    
        /* Empty method definition. */
        public void mouseExited(MouseEvent e) {
        }
    
       /* Empty method definition. */
        public void mouseClicked(MouseEvent e) {
           
        }
    
    }
    
    file5
    import java.awt.*;
    import javax.swing.*;
    
    public class SquarePanel extends JPanel {
    	String content;
    	
    	public SquarePanel() {
    		content = "";
    	}
    	
    	public String getContent() {
    		return content;
    	}
    	
    	public void setContent(String c) {
    		content = c;
    	}
    }

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: making a chess board gui

    Think through your logic in your nested for loop as it's wrong, and in particular your if (j != 0) bit since you end up trying to add the same JPanel twice to the grid, and that will never work. Instead you have to add a new JPanel to the grid each time. Work it out first on paper as if you were drawing white and black squares on paper starting with a 2 by 2 grid, and see what happens.

  6. #6
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: making a chess board gui

    Another problem with your graphics is that usually when you override a graphics method such as paintComponent, you'll want to call the super's method somewhere in this code, often as the first call in the method, so that house-keeping graphics can be done, such as erasing old images to make way for the new. So for instance, you'll probably want to change every paintComponent method to something like so:

    Java Code:
       public void paintComponent(Graphics g) {
          super.paintComponent(g);  // *** Add this *** 
    
          // rest of your graphics code goes here
    
       }

  7. #7
    yemista is offline Member
    Join Date
    Oct 2011
    Posts
    41
    Rep Power
    0

    Default Re: making a chess board gui

    ok, its working now, thanks for all your help!

  8. #8
    yemista is offline Member
    Join Date
    Oct 2011
    Posts
    41
    Rep Power
    0

    Default Re: making a chess board gui

    ok, Ive condensed the code very much, however, not all the panels are displaying on top of each other. it was working fine earlier, and im not sure what exactly i changed to cause it to do this. sorry if this is a simple question, but i am new to gui programming, and tired because ive been working on this all day. I got the logic mostly done for the chess portion of the code, now its just a matter of linking the two.

    Java Code:
    file1
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    
    public class MoveListener implements MouseListener {
    	private int first_click;
    	private SquarePanel first_source;
    	private Game game;
    	
    	public MoveListener(Game game) {
    		first_click = 0;
    		this.game = game;
    	}
    	
    	
    	/* Empty method definition. */
        public void mousePressed(MouseEvent e) {
    		SquarePanel p = (SquarePanel)e.getSource();
    		String content = null;
    		
    		if(first_click == 0) {
    			first_source = p;
    			++first_click;
    		}
    		else {
    			first_click = 0;
    			content = first_source.getContent();
    			first_source.setContent("");
    			first_source.repaint();
    			p.setContent(content);
    			p.repaint();
    			
    		}
    		
    		//System.out.println(content);
    		//System.out.println(first_click);
    	}
    
        /* Empty method definition. */
        public void mouseReleased(MouseEvent e) {
        }
    
        /* Empty method definition. */
        public void mouseEntered(MouseEvent e) {
        }
    
        /* Empty method definition. */
        public void mouseExited(MouseEvent e) {
        }
    
        public void mouseClicked(MouseEvent e) {
           
        }
    
    }
    
    file2
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.border.*;
    
    public class SquarePanel extends JPanel {
    	private String content;
    	private int x;
    	private int y;
    	private int color;
    	
    	public SquarePanel(int color, int x, int y) {
    		content = "";
    		this.color = color;
    		this.x = x;
    		this.y = y;
    		Border blackline = BorderFactory.createLineBorder(Color.black);
    		setBorder(blackline);
    		this.setLayout(new GridBagLayout());
    	}
    	
    	public void paintComponent(Graphics g) {
    		super.paintComponent(g);
    		int width = getWidth();
    		int height = getHeight();
    		
    		if(color == Colors.WHITE)
    			g.setColor(Color.white);
    		else
    			g.setColor(Color.green);
    			
    		g.fillRect(0, 0, width, height);
    		g.setColor(Color.black);
    		g.drawString(x+","+y,width/2,height/2);
    	}
    	
    	public String getContent() {
    		return content;
    	}
    	
    	public void setContent(String c) {
    		content = c;
    	}
    	
    	public int getX() {
    		return x;
    	}
    	
    	public int getY() {
    		return y;
    	}
    }
    
    
    file3
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    
    public class GameFrame extends JFrame {
    	private JPanel[][] squares;
    	
    	public GameFrame(Game game) {
    		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		Container con = this.getContentPane();
    		setSize(800,800);
    		setLocation(0,0);
    		con.setLayout(new GridLayout(8,8));
    		SquarePanel pane = null;
    		SquarePanel lastpanel = null;
    		MouseListener listener = new MoveListener(game);
    		squares = new JPanel[8][8];
    		
    		for(int i = 7; i >= 0; --i) {	
    			for(int j = 0; j <= 7; ++j) {
    				lastpanel = new SquarePanel(0,j,i);
    				pane = lastpanel;				
    				pane.addMouseListener(listener);
    				con.add(pane);
    				squares[j][i] = pane;
    			}
    		}
    	
    		setVisible(true);
    		
    	}
    	
    	public static void main(String[] args) {
    		new GameFrame(new Game());
    	}
    
    }

  9. #9
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: making a chess board gui

    Quote Originally Posted by yemista View Post
    ok, Ive condensed the code very much, however, not all the panels are displaying on top of each other. it was working fine earlier, and im not sure what exactly i changed to cause it to do this. sorry if this is a simple question, but i am new to gui programming, and tired because ive been working on this all day.
    You state "sorry if this is a simple question" but neglect to ask a question, so there's limited help we can give. If you don't know where the problem is then debug your code with println statements to find out. Please come back if you've found your problem, can describe it, and have an answerable question to ask.

  10. #10
    yemista is offline Member
    Join Date
    Oct 2011
    Posts
    41
    Rep Power
    0

    Default Re: making a chess board gui

    Sorry about that. I dont know how to debug gui code with println statements because in order to do that you have to understand how the components interact with each other. Currently, the problem is that instead of displaying the panels in a grid pattern, they are all stacked in the upper left corner. Depending on where in the frame i click, that determines which one is on top of the stack. I have attached an image of how it looks. Its supposed to look like a grid of 64 green squares each with their coordinates printed on them
    Attached Thumbnails Attached Thumbnails making a chess board gui-window.png  

  11. #11
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: making a chess board gui

    Tricky error, but one that has tripped me up in the past (which is why I can catch it -- and now you can too):

    Java Code:
    public class SquarePanel extends JPanel {
        private int x;
        private int y;
    
    
        // ... code removed for sake of brevity
    
    
         
        public int getX() {
            return x;
        }
         
        public int getY() {
            return y;
        }
    }
    Your getX() and getY() methods are overriding similar methods of JPanel and this is messing up the placement of your JPanels as Swing thinks that they should be placed where getX() and getY() tells them to place it.

    Solution: rename those methods so they don't mess up the super methods. Perhaps you could call them

    Java Code:
       public int getXValue() {
         return x;
      }
    
       public int getYValue() {
         return y;
      }
    Or something else -- anything as long as it doesn't override critical methods of the super class.

  12. #12
    yemista is offline Member
    Join Date
    Oct 2011
    Posts
    41
    Rep Power
    0

    Default Re: making a chess board gui

    ok, that was a tricky one! thanks for your help!

Similar Threads

  1. Replies: 2
    Last Post: 06-29-2011, 09:08 AM
  2. Replies: 10
    Last Post: 02-07-2011, 09:08 AM
  3. Help with Chess GUI
    By Lord Voldemort in forum AWT / Swing
    Replies: 9
    Last Post: 01-24-2011, 05:38 PM
  4. Making a dart-board
    By MarsTeam in forum Advanced Java
    Replies: 6
    Last Post: 06-22-2010, 07:54 PM
  5. need help making a game board
    By Don k in forum New To Java
    Replies: 2
    Last Post: 04-30-2010, 12:09 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •