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 5 of 5

Thread: Newbeginner - Something wrong with my GUI chess pattern

  1. #1
    Junior Member
    Join Date
    May 2011
    Posts
    21
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Question [SOLVED] Newbeginner - Something wrong with my GUI chess pattern

    Hello everyone,

    I'm new at programming but everyone starts as newbeginner, right? I'm supposed to make chess patterns on a panel in different sizes but something goes wrong.

    It work fine but it doesn't. I think I'm missing something but what I don't know.

    Here's the code:

    import java.awt.*;
     
    public class ChessPattern {
     
    	public static void main(String[] args0){
     
    		DrawingPanel panel = new DrawingPanel(420, 300);
    		panel.setBackground(Color.darkGray);
     
    		Graphics g = panel.getGraphics();
     
    		square(g, 0, 0, 10, 5, 5);
    		square(g, 210, 30, 15, 4, 4);
    		square(g, 60, 40, 15, 7, 7);
     
    	}
    		//method to draw chess pattern squares
    		public static void square(Graphics g, int x, int y, int size, int squarecolumn, int squarerow){
    			//the column
    			for(int j = 0; j < squarecolumn; j++){
    				//the row
    				for(int i = 0; i < squarerow; i++){
    					//if i is even for row and column then gray
    					if(i%2 == 0 && j%2 == 0){
    						g.setColor(Color.gray);
    						//if i is odd for row and column then gray 
    					}else if(i%2 == 1 && j%2 == 1){
    						g.setColor(Color.gray);
    						//if i is even for row and j is odd for column then white
    					}else if(i%2 == 0 && j%2 == 1){
    						g.setColor(Color.white);
    						//if i is odd for row and j is even for column then white
    					}else if(i%2 == 1 && j%2 == 0){
    						g.setColor(Color.white);
    					}
    					//where and how much to fill going by row
    					g.fillRect(x+i*size,y+j*size, size, size);
     
    				}
    				//where and how much to fill going by column
    				g.fillRect(x, y+j*size, size, size);
     
    			}
    			//Drawing the reactangle border
    			g.setColor(Color.black);
    			g.drawRect(x, y, size*squarecolumn, size*squarerow);
     
    		}	
    }

    and here't how it looks:



    I found out that everytime I let the squares be even x even size then I get a pattern like the right while odd x odd size gets me the chess pattern I want.

    Ex: square(g, 0, 0, 10, 5, 5);
    square(g, 210, 30, 15, 4, 4);
    square(g, 60, 40, 15, 7, 7);

    Could someone help me out and tell/explain me what I am missing or doing wrong?
    Thanks^^

    PS: For people who wants the DrawingPanel class which was on the CD as support to GUI programming:

    /*
    Stuart Reges and Marty Stepp
    07/01/2005
     
    The DrawingPanel class provides a simple interface for drawing persistent
    images using a Graphics object.  An internal BufferedImage object is used
    to keep track of what has been drawn.  A client of the class simply
    constructs a DrawingPanel of a particular size and then draws on it with
    the Graphics object, setting the background color if they so choose.
     
    To ensure that the image is always displayed, a timer calls repaint at
    regular intervals.
    */
     
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.imageio.*;
    import javax.swing.*;
    import javax.swing.event.*;
     
    public class DrawingPanel implements ActionListener {
        public static final int DELAY = 250;  // delay between repaints in millis
     
        private static final String DUMP_IMAGE_PROPERTY_NAME = "drawingpanel.save";
        private static String TARGET_IMAGE_FILE_NAME = null;
        private static final boolean PRETTY = true;  // true to anti-alias
        private static boolean DUMP_IMAGE = false;  // true to write DrawingPanel to file
     
        private int width, height;    // dimensions of window frame
        private JFrame frame;         // overall window frame
        private JPanel panel;         // overall drawing surface
        private BufferedImage image;  // remembers drawing commands
        private Graphics2D g2;        // graphics context for painting
        private JLabel statusBar;     // status bar showing mouse position
        private long createTime;
     
        static {
            TARGET_IMAGE_FILE_NAME = System.getProperty(DUMP_IMAGE_PROPERTY_NAME);
            DUMP_IMAGE = (TARGET_IMAGE_FILE_NAME != null);
        }
     
        // construct a drawing panel of given width and height enclosed in a window
        public DrawingPanel(int width, int height) {
            this.width = width;
            this.height = height;
            this.image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
     
            this.statusBar = new JLabel(" ");
            this.statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));
     
            this.panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
            this.panel.setBackground(Color.WHITE);
            this.panel.setPreferredSize(new Dimension(width, height));
            this.panel.add(new JLabel(new ImageIcon(image)));
     
            // listen to mouse movement
            MouseInputAdapter listener = new MouseInputAdapter() {
                public void mouseMoved(MouseEvent e) {
                    DrawingPanel.this.statusBar.setText("(" + e.getX() + ", " + e.getY() + ")");
                }
     
                public void mouseExited(MouseEvent e) {
                    DrawingPanel.this.statusBar.setText(" ");
                }
            };
            this.panel.addMouseListener(listener);
            this.panel.addMouseMotionListener(listener);
     
            this.g2 = (Graphics2D)image.getGraphics();
            this.g2.setColor(Color.BLACK);
            if (PRETTY) {
                this.g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                this.g2.setStroke(new BasicStroke(1.1f));
            }
     
            this.frame = new JFrame("Drawing Panel");
            this.frame.setResizable(false);
            this.frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    if (DUMP_IMAGE) {
                        DrawingPanel.this.save(TARGET_IMAGE_FILE_NAME);
                    }
                    System.exit(0);
                }
            });
            this.frame.getContentPane().add(panel);
            this.frame.getContentPane().add(statusBar, "South");
            this.frame.pack();
            this.frame.setVisible(true);
            if (DUMP_IMAGE) {
                createTime = System.currentTimeMillis();
                this.frame.toBack();
            } else {
                this.toFront();
            }
     
            // repaint timer so that the screen will update
            new Timer(DELAY, this).start();
        }
     
        // used for an internal timer that keeps repainting
        public void actionPerformed(ActionEvent e) {
            this.panel.repaint();
            if (DUMP_IMAGE && System.currentTimeMillis() > createTime + 4 * DELAY) {
                this.frame.setVisible(false);
                this.frame.dispose();
                this.save(TARGET_IMAGE_FILE_NAME);
                System.exit(0);
            }
        }
     
        // obtain the Graphics object to draw on the panel
        public Graphics2D getGraphics() {
            return this.g2;
        }
     
        // set the background color of the drawing panel
        public void setBackground(Color c) {
            this.panel.setBackground(c);
        }
     
        // show or hide the drawing panel on the screen
        public void setVisible(boolean visible) {
            this.frame.setVisible(visible);
        }
     
        // makes the program pause for the given amount of time,
        // allowing for animation
        public void sleep(int millis) {
            try {
                Thread.sleep(millis);
            } catch (InterruptedException e) {}
        }
     
        // take the current contents of the panel and write them to a file
        public void save(String filename) {
            String extension = filename.substring(filename.lastIndexOf(".") + 1);
     
            // create second image so we get the background color
            BufferedImage image2 = new BufferedImage(this.width, this.height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image2.getGraphics();
            g.setColor(panel.getBackground());
            g.fillRect(0, 0, this.width, this.height);
            g.drawImage(this.image, 0, 0, panel);
     
            // write file
            try {
                ImageIO.write(image2, extension, new java.io.File(filename));
            } catch (java.io.IOException e) {
                System.err.println("Unable to save image:\n" + e);
            }
        }
     
        // makes drawing panel become the frontmost window on the screen
        public void toFront() {
            this.frame.toFront();
        }
    }
    Last edited by JavaN00b; May 6th, 2011 at 05:27 AM. Reason: I though I should change the topic so people don't keep looking here to help me when there's no more need.^^


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Newbeginner - Something wrong with my GUI chess pattern

    Just have time for a quick glance but immediately see something amiss - do not paint to a graphics object of a Swing component by calling getGraphics(): place all your painting routines in the paintComponent method (see Painting in AWT and Swing ) Whether not this is directly your problem I can't say right now, but I'd highly recommend adjusting your code to paint the recommended way first, then re-post the code if you still have issues

  3. #3
    Junior Member
    Join Date
    May 2011
    Posts
    21
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Newbeginner - Something wrong with my GUI chess pattern

    Ahhh, no in the book there was an intro to the to GUI where you use the support class(made by the authors) which I posted under the PS. That class uses the getGraphics(); method and that's the only one learned so far. So it should be able to handle it without using paintComponent.

    I don't think it's that class that does it, I think it's somewhere in my algorithm it's failing. The problem is I can't see where or why. For me it's quite logical and should work fine.

    Still thanks for trying.

    PS: paintComponent is the last chapter of this book where they really go into the GUI. I'm not that far yet, lol.

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Newbeginner - Something wrong with my GUI chess pattern

    I'm curious what book you have: if it teaches you to paint to swing components in this way the author has lost all credibility with me. I know this isn't directly the problem, but it is best practice. You can listen to your book, or some stranger on the internet: your choice

    Now that I've had more time to look at the code, why is there the second fillRect call at the end of your inside for loop (with i)? Comment out that line and see what happens...

  5. #5
    Junior Member
    Join Date
    May 2011
    Posts
    21
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Newbeginner - Something wrong with my GUI chess pattern

    It's called Building Java Programs - A back to basic Approach by Stuart Reges and Marty Stepp : Building Java Programs: A Back to Basics Approach, by Stuart Reges and Marty Stepp

    I like it quite a lot since it teach me the way I like best. You learn something, you get some examples on how you can use it, you get some review questions, you get exercises with the stuff learned in the chapter and then you get small projects where you use what you learned in this chapter together with the stuff used in the previous chapters. Something I missed in the java class I had where we used BlueJ book and had a really bad teacher.

    The first (inside) for loop is for making the row squares, the second (outside) for loop is for making the column squares. The first loop makes the row squares when it ends the second loop makes a jump down the column and then you get the first loop to make the row pattern again and so on.

    Edit: I found out my problem... it's the second fillrect that's the problem. I make it draw again and this time I place at the wrong place which makes it overlap since the other loop will affect the inner loop. I had forgotten that I place "j" already inside the inner loop.
    Thanks a lot for pointing out that I had 2 fillrect when there's no need to do so. It helped a lot and made a lot of sense too.

    Now I can move to chapter 4 after wasting half day trying to figure out where I went wrong, lol. Funny thing is that after finding out the problem, I'm kind of recharged and want to continue with chapter 4's exercises. (read the chapter already and done the rest of chapter 3's exercises)

    I shall come back when I go "huh" at my code again.

Similar Threads

  1. checking for draw by repetition in chess app
    By aisthesis in forum Algorithms & Recursion
    Replies: 0
    Last Post: February 16th, 2011, 02:40 AM
  2. Chess Problem
    By pmg in forum What's Wrong With My Code?
    Replies: 4
    Last Post: February 10th, 2011, 12:07 PM
  3. Help with regex pattern
    By b_jones10634 in forum Java Theory & Questions
    Replies: 4
    Last Post: September 24th, 2010, 03:59 PM
  4. Simple Chess program
    By x3rubiachica3x in forum What's Wrong With My Code?
    Replies: 23
    Last Post: September 22nd, 2010, 11:12 AM
  5. a new pattern with a new architecture
    By mcgrow in forum Web Frameworks
    Replies: 0
    Last Post: August 4th, 2010, 02:28 PM