1

Hello all I have this problem that I can't seem to fix. I've been given some code and have to make a "tic tac toe" game. Fairly primitive. At the moment what it want's me to do is take user input (it just asks for what row / column you want to place the marker) and it is meant to draw an oval on the appropriate square of the board. My current code is as following the work has specified that I make a new class to deal with user input.

I am currently just mucking around with trying to get it to add new items to the JFrame but am having little success. I have a dummy call for input, it doesn't check to see what I've typed it just calls an oval that SHOULD sit in the first square in the top left corner. I can get the object to draw onto the JFrame (albeit it takes up the whole frame) but it is always BEHIND the actual board (ie: if I stretch the frame I can see the circle). I've tried adding JPanels and so forth so that they sit on top of the board but so far I am having little luck.

Here is the code for creating the Oval which I was given for the task. All I am doing is instantiating a new oval with position (0,0,10,10). When it draws however it takes up the WHOLE JFrame but it is also BEHIND the actual board...... any ideas?

package lab4;

import javax.swing.*;
import java.awt.*;

/** Oval Supplier Class 
 * Author: David D. Riley
 * Date: April, 2004
 */
public class Oval extends JComponent  {

    /** post:   getX() == x  and  getY() == y
     *          and  getWidth() == w  and getHeight() == h
     *          and  getBackground() == Color.black
     */
    public Oval(int x, int y, int w, int h)  {
        super();
        setBounds(x, y, w, h);
        setBackground(Color.black);
    }

    /** post:   this method draws a filled Oval
     *          and  the upper left corner of the bounding rectangle is (getX(), getY()) 
     *          and  the oval's dimensions are getWidth() and getHeight()
     *          and  the oval's color is getBackground()
     */
    public void paint(Graphics g)  {
        g.setColor( getBackground() );
        g.fillOval(0, 0, getWidth()-1, getHeight()-1);
        paintChildren(g);
   }

}

EDIT: THIS IS NOW THE CODE WE ARE LOOKING AT--

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package lab4;

/**
 *
 * @author Scott
 */
import java.awt.*;
import java.util.Scanner;
import javax.swing.*;

public class GameBoard {

    private JFrame win;
    private int count = 1;

    //Create new GUI layout
    GridLayout layout = new GridLayout(3, 3);
    JPanel panel = new JPanel(layout);

    //Create a new Array of Rectangles
    Rectangle[][] rect = new Rectangle[3][3];

    public GameBoard() {


        //Create new JFrame + Set Up Default Behaviour
        win = new JFrame("Tic Tac Toe");

        win.setBounds(0, 0, 195, 215);
        win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        win.setResizable(true);

        //Loop goes through each line of the array. It creates a new rectangle
        //determines it's colour based on modulus division
        //Add's the rectangle to the JPanel.
        for (int i = 0; i < rect.length; i++) {
            for (int j = 0; j < rect[i].length; j++) {
                rect[i][j] = new Rectangle(0, 0, 1, 1);
                if (count % 2 != 0) {
                    rect[i][j].setBackground(Color.black);
                } else {
                    rect[i][j].setBackground(Color.red);
                }
                panel.add(rect[i][j]);
                count++;
            }
        }


        //Sets the game to be visible.
        win.add(panel);
        win.setVisible(true);
        //userInput();
    }

    private void userInput() {
    Scanner scan = new Scanner(System.in);
    }
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Scott
  • 465
  • 3
  • 10
  • 22
  • Why are you using `paint`?? Apart from the fact that you're not calling `super.paint` you should be using `paintComponent` – MadProgrammer Sep 19 '12 at 06:29
  • Okay, I had a quick look at your code, it there is absolutely no way that your `GameBoard` method could work. `JFrame` does not accept `Rectangle` via any `add` method that I know, it generally requires a `Component`. Without an appropriate [SSCCE](http://sscce.org/) it's going to be a lot harder to help you – MadProgrammer Sep 19 '12 at 06:34
  • How are you adding your Oval components to the JFrame? If you simply call add(new Oval()) and you have kept the default LayoutManager of the JFrame's content pane, then you are with a BorderLayout which will override your calls to setBounds and make the oval take the whole area. – Guillaume Polet Sep 19 '12 at 07:32
  • Yep that is pretty much what it is doing except that I also falls behind whatever else has been drawn onto the frame. Could I resolve this by adding a JPanel or something similar in the mix? – Scott Sep 19 '12 at 07:36
  • **never-ever** do any manual sizing/locating in Swing, that's the exclusive task of a suitable LayoutManager – kleopatra Sep 19 '12 at 08:47
  • @kleopatra: The homework tag is now [obsolete](http://meta.stackexchange.com/questions/147100/the-homework-tag-is-now-officially-deprecated) – dario_ramos Sep 19 '12 at 15:08
  • @dario_ramos thanks for the heads up, wasn't aware of the change :-) – kleopatra Sep 19 '12 at 15:45
  • Ok so I've reworked part of the homework to use a grid layout. I've appended my original post. This final part of the homework, as was the case before is to have it place an over into a specified square determined by user input (for example if I type in 1 1 it will put a circle in the top left corner). I've tried to do this a few ways and get stuck every time. With grid layout once I have added all the rectangles I can't simply replace them. I tried adding a JPanel to each part in the grid and instead add the rectangle to that but no luck.... any ideas how this could be achieved? – Scott Oct 02 '12 at 08:15
  • I am assuming that the only way to do it will be to take the user input, remove all the items, re-add and then repaint them? Because I can't just replace a specific item..... – Scott Oct 02 '12 at 08:19

2 Answers2

1

Let's start with your oval class...

This is a VERY bad idea...

public void paint(Graphics g)  {
    // No super.paint(g) call, hello to a world of pain...
    // Paint some stuff
    g.setColor( getBackground() );
    g.fillOval(0, 0, getWidth()-1, getHeight()-1);
    // Then draw the children over it...???
    paintChildren(g);
}

This is a better approach.

protected void paintComponent(Graphics g)  {
    super.paintComponent(g);
    g.setColor( getBackground() ); // Might want to pick a better color...
    g.fillOval(0, 0, getWidth()-1, getHeight()-1);

}

At a guess, I suggest that your window is using a layout manager that is overriding your setBounds call

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I can't change the oval class it was given to me by my tutor so that has to stay as it is. I'm using the default layout manager which I believe is just the flow layout, would I be best advised to look into another layout manager? The page that gives me guidelines doesn't specify that I would need to do that. I was also under the assumption that the things that were added AFTER something else went on top, like stacking sheets of paper....Been doing Java most of the day now so I'll give it a rest for an hour or so and see if I get a ray of light or an answer between now and then. – Scott Sep 19 '12 at 07:20
  • I'd start with a `GridLayout` – MadProgrammer Sep 19 '12 at 07:28
  • 1
    @gRnt probably not on option to tell your tutor to come over and learn some Swing before teaching you worst practices ;-) – kleopatra Sep 19 '12 at 08:46
  • I don't think the layout is your main problem, it's not helping. From the sounds of things, there's some custom painting going on that is painting over you components, especially if your following the examples provided by your tutor :P – MadProgrammer Sep 19 '12 at 08:57
0

Answer ended up being that I need to stick with the flow layout, manually size the rectangles and use a JLayeredPane instead. Was not aware this existed, talked to my lecturer who said that my thought process was right and that was the way he intended for me to do it......what a pain but all done thanks to those that helped.

Scott
  • 465
  • 3
  • 10
  • 22