So, I'm trying to make a game of tic tac toe using JFrame and JPanel.

This creates the board image 3x3 .

package book;

import javax.swing.JPanel;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JButton;

public class Beginning extends JPanel {
    public void drawBoard(Graphics d){

        int r = getWidth();
        int a = getHeight();
        int r1 = r/3;
        int t = a/3;
        Graphics2D g2 = (Graphics2D) d;
        g2.setStroke(new BasicStroke(10));
        float alpha= (float) 0.2;
        Color color = new Color(0,0,1,alpha);
        g2.setPaint(color);
        d.drawLine(r1, 0, r1, a);
        d.drawLine(2*r1,0,2*r1,a);
        d.drawLine(0,t,r,t);
        d.drawLine(0,2*t,r,2*t);
        add(new JButton("Hello"));
    }
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        setBackground(Color.white);
        g.setColor(Color.blue);
        drawBoard(g);

    }
}

It looks like this: Board.png
Board

Anyway:Im trying to add buttons in the squares and was stuck on how to do it.
This is my code so far:

    import java.awt.FlowLayout;
    import java.util.Scanner;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import java.util.ArrayList;
    import java.util.Arrays;


    public class BeginningTest extends JFrame {
            private JButton reg;

            public BeginningTest(){
                //setLayout(new FlowLayout());  
                Beginning na = new Beginning();
                na.setSize(200,400);
                add(na);
                setTitle("TicTacToe");

                // This is where I tried to add the first button
                JPanel ga = new JPanel();
                ga.add(new JButton());
                add(ga);

                setDefaultCloseOperation(EXIT_ON_CLOSE);
                setSize(700, 700);
                setLocationRelativeTo(null);
                setVisible(true);     
            }
            public static void main(String[] args){
                new BeginningTest();    
            }
    }

This is making something very weird, anyway any help would be great thanks/.

Try a GridLayout.
FYI: It is also possible to do this entirely without buttons, it would be more complicated though
(since you'd need to compute the clicked square from the coordinates of the mouse click).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.