+ 1

Creating GUI Board Java--Buttons

Hi guys, I'm looking to make a GUI board for my own version of Tic Taco Toe. Currently using Java.AWT* and javax.swing*. I'm aware that there are a plethora of projects with this game, but I don't want to "cheat" or copy directly from existing sources because I believe it defeats the purpose of learning. I want the experience of problem-solving and being creative . Any assistance and input would be helpful. I'm still a beginner. My goal with this project is to advance the skill of algorithmic thinking and to complete a first project. I have a separate Logic Class that I'm very happy with -- it works beautifully. I ran into difficulty figuring out a better way for the user to interact with the game board. I'm working making the board interactive if possible-- maybe button clicks and the game state updates...that sort of thing. Any other ideas are welcome. Thank you so much. Currently using JButton to make a button board. how do i get my buttons to be in a grid layout? I'd like 9 buttons to be in a grid of 3 rows and 3 columns. If I use grid layout, how do I get it to not take up the entire portion of the the JFrame? Right now the 9 buttons line up at the top of my JFrame. How do I get it to be in the center of the JFrame? Is there a cleaner way than the code I have below? public class testBoard extends JFrame { JPanel buttonPanel; JButton b1,b2,b3,b4,b5,b6,b7, b8, b9; String text[]= {"1","2","3","4","5","6","7","8","9"}; public testBoard(){ this.setTitle("Tic Tac Toe"); this.setSize(1000, 1000); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); b1=new JButton(); b1.setText(text[0]); b2=new JButton(); b2.setText(text[1]); b3=new JButton(); b3.setText(text[2]); b4=new JButton(); b4.setText(text[3]); b5=new JButton(); b5.setText(text[4]); b6=new JButton(); b6.setText(text[5]); b7=new JButton(); b7.setText(text[6]); b8=new JButton(); b8.setText(text[7]);

5th Feb 2020, 6:27 PM
Mich
Mich - avatar
4 odpowiedzi
+ 2
JFrame f=new JFrame("New"); f.add(b1); f.add(b2); ... f.setLayout(new GridLayout()); May be this can works for you... You already extending JFrame so try like this.add(b1);.... this.setLayout(new GridLayout(x, y)) ; x, y are row, column values....
5th Feb 2020, 7:21 PM
Jayakrishna 🇮🇳
+ 1
buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout(3,3) ); JButton[] buttons = new JButton[9]; for (int i=0; i<9; i++) { buttons[i] = new JButton( String.valueOf(i) ); buttonPanel.add(buttons[i]); } add(buttonPanel);
6th Feb 2020, 7:30 AM
zemiak
0
Thank you. I will try it. You're amazing!
5th Feb 2020, 7:27 PM
Mich
Mich - avatar
0
thank you, Zemiak, I apology for my late response. I really appreciate your help as well.
10th Feb 2020, 11:32 PM
Mich
Mich - avatar