Java hangman program gone horribly wrong - java

I am a beginner at Java, and was required to throw together an application for a Java final project. I wanted to do hangman (Seemed easy at the time). This is EXTREMELY DIFFICULT for me. Here is my code so far. (it's really an abomination of about 10 open source hangman games thrown together). See bottom for my question.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
public class Hangman implements ActionListener {
JFrame frame;
private String[] wordList = {"computer","java","activity","alaska","appearance","article",
"automobile","basket","birthday","canada","central","character","chicken","chosen",
"cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
"establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
"hurried","identity","importance","impossible","invented","italian","journey","lincoln",
"london","massage","minerals","outer","paint","particles","personal","physical","progress",
"quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
"strike","successful","sudden","terrible","traffic","unusual","volume","yesterday" };
public String mysteryWord;
public int lives;
private boolean finished = false;
private boolean won = false;
private Button a[];
public boolean used[] = new boolean[26];
public static void main (String[] args) {
Hangman gui = new Hangman();
gui.go();
}
class myDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
setBackground(Color.white);
g.setColor(Color.gray);
g.fillRect(50, 200, 150, 20);
g.fillRect(90,20,10,200);
g.fillRect(90,20,60,10);
g.setColor(Color.black);
g.fillRect(145,20,5,25);
g.setColor(Color.green);
if (lives < 6 )
g.drawOval(132,45,30,30);
if (lives < 5 )
g.drawLine(147,75,147,100);
if (lives < 4 )
g.drawLine(147,100,167,133);
if (lives < 3 )
g.drawLine(147,100,127,133);
if (lives < 2 )
g.drawLine(147,75,167,85);
if (lives < 1 )
g.drawLine(147,75,127,85);
StringBuffer guessed = new StringBuffer();
for (int cl = 0; cl < mysteryWord.length(); cl++) {
if (used[(int)mysteryWord.charAt(cl)-65])
guessed.append(mysteryWord.charAt(cl));
else
guessed.append(".");
}
g.drawString(guessed.toString(),75,230);
//currentWordLA.setText("Current word: " + mysteryWord);
if (lives < 1) {
g.setColor(Color.white);
g.fillRect(70, 200, 200, 30);
g.setColor(Color.black);
g.drawString(mysteryWord.toString(),75,230);
Font fff = new Font("Helvetica",Font.BOLD,36);
g.setFont(fff);
g.setColor(Color.red);
g.drawString("You lose!",200,100);
finished = true;
}
if (won) {
Font fff = new Font("Helvetica",Font.BOLD,36);
g.setFont(fff);
// Color red=new Color.red
g.setColor(Color.red);
g.drawString("You Win!",200,100);
finished = true;
}
}
}
public void go() {
///////////////////////DESIGN BEGIN//////////////////////////////////////////////
frame = new JFrame("Hangman");
JPanel topPanel = new JPanel();
myDrawPanel noosePanel = new myDrawPanel();
JPanel bottomPanel = new JPanel();
JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new GridLayout( 2, 0) );
bottomPanel.setLayout( new GridLayout( 0, 2) );
scorePanel.setSize(20,100);
noosePanel.setBorder(BorderFactory.createTitledBorder("Your progress."));
topPanel.setBorder(BorderFactory.createTitledBorder("Your arsenal."));
scorePanel.setBorder(BorderFactory.createTitledBorder("Your score."));
frame.add(topPanel);
frame.add(bottomPanel);
bottomPanel.add(scorePanel);
bottomPanel.add(noosePanel);
//Just the stats panel.
JPanel stats = new JPanel();
JLabel currentWordLA = new JLabel("Current word:");
JLabel triedLettersLA = new JLabel("Tried letters:");
JLabel triesLeftLA = new JLabel("Tries remaining:");
JButton restart = new JButton("Reset");
currentWordLA.setFont(new Font("Verdana", Font.PLAIN, 10));
currentWordLA.setForeground(Color.black);
triedLettersLA.setFont(new Font("Verdana", Font.PLAIN, 10));
triedLettersLA.setForeground(Color.black);
triesLeftLA.setFont(new Font("Verdana", Font.PLAIN, 10));
triesLeftLA.setForeground(Color.black);
restart.setFont(new Font("Verdana", Font.PLAIN, 16));
restart.setForeground(Color.red);
stats.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(20,0,0,0);
c.anchor = GridBagConstraints.LINE_START;
stats.add(currentWordLA, c);
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.LINE_START;
stats.add(triedLettersLA, c);
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.LINE_START;
stats.add(triesLeftLA, c);
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.LINE_START;
stats.add(restart, c);
scorePanel.add(stats);
///////////////////////DESIGN END//////////////////////////////////////////////
///////////////////////ALPHABET BEGIN//////////////////////////////////////////
int i;
StringBuffer buffer;
a = new Button[26];
topPanel.setLayout( new GridLayout( 4,0, 10, 10) );
for (i = 0; i <26; i++) {
buffer = new StringBuffer();
buffer.append((char)(i+65));
a[i] = new Button(buffer.toString());
a[i].setSize(100,100);
a[i].addActionListener( this );
topPanel.add(a[i]);
}
///////////////////////ALPHABET END//////////////////////////////////////////
//Just shows the entire window.
frame.setSize(500, 500);
frame.setResizable(false);
frame.setVisible(true);
//////////////////////GAMEPLAY BEGIN////////////////////////////////////////
lives = 6;
mysteryWord = wordGen();
}
//Returns a random word from the wordList bank.
private String wordGen() {
return wordList[0 + (int)(Math.random() * ((63 - 0) + 1)) ]; //Make sure to set these to nonprinted chars eventually
}
public void consultWord(int letter) {
if (finished == false) {
boolean found = false;
boolean www = false;
if (used[letter] = false) {
for (int cl = 0 ; cl < mysteryWord.length(); cl++) {
if (mysteryWord.charAt(cl)==((char)(letter+65))) found = true;
}
if (found == false)
lives = lives - 1;
}
used[letter] = true;
for (int cl = 0; cl < mysteryWord.length(); cl++) {
if (!used[(int)(mysteryWord.charAt(cl)) - 65]) www = true;
}
if (www = false) won = true;
frame.repaint();
}
}
public void actionPerformed( ActionEvent e) {
int i;
for (i = 0; i < 26; i++) {
if (e.getSource() == a[i]) {
consultWord(i); }
}
}
}
At the moment this doesn't work. I run it, and tons of thread exeption errors come up. (It compiles beautifully). The first line it takes me to is
if (used[(int)mysteryWord.charAt(cl)-65])
I'm not sure what the issue is with this line. Also, the original author used the number 65. I tweaked my code and used my own variables so that I understood how it worked. But the number 65 and where it came from, I can't figure out for the life of me. Any ideas?
And I need to know what is causing all the thread exceptions. The GUI builds nicely. It's just all the math and triggers that mess things up. (The GUI I built all by myself! :) )
Exception
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 34
at Hangman$myDrawPanel.paintComponent(Hangman.java:55)
at javax.swing.JComponent.paint(JComponent.java:1054)
at javax.swing.JComponent.paintChildren(JComponent.java:887)
at javax.swing.JComponent.paint(JComponent.java:1063)
at javax.swing.JComponent.paintChildren(JComponent.java:887)
at javax.swing.JComponent.paint(JComponent.java:1063)
at javax.swing.JComponent.paintChildren(JComponent.java:887)
at javax.swing.JComponent.paint(JComponent.java:1063)
at javax.swing.JLayeredPane.paint(JLayeredPane.java:585)
at javax.swing.JComponent.paintChildren(JComponent.java:887)

This is mostly not a direct answer to your question, but it is relevant to the larger issue of learning to write software ... which is your overall goal. (And there's a real answer at the bottom.)
You write:
(it's really an abomination of about 10 open source hangman games thrown together)
Taking a bunch of existing programs (of dubious quality *) and mashing them together is NOT a good way to create software.
You inherit the problems of functionality and style in the existing code that you have "harvested".
You add a bunch of new functionality and style problems caused by mismatches between the different code bases ... and your conception.
Code reuse can be a good thing, but you need to be disciplined and selective:
Do design your own code ... following the design principles that you have been taught.
Do reuse at the library level, using well-engineered libraries.
Don't reuse by copy-and-pasting.
Don't reuse code (or libraries) that looks like a dog's breakfast. (If the author is sloppy with his/her code style and API design, that's a bad sign for other quality issues.)
(* The fact that you are seeing obscure numbers like 65 embedded in the code is a sign of poor code quality. The author could and should have written that as 'A'.)
In fact, this might be the root of your bug, since it looks like your "mystery" words are in lowercase. 'a' - 'A' is 32, and that is larger than the bounds of your used array.
And this brings us back to my main point. Because, apparently, in your code mashing you have failed to understand the implied invariants of the code you copied ... and broken them. The problematic statement that is throwing the exception is designed to work with uppercase-only words ... but you've changed that.

The 65 is the ASCII character code for the letter 'A'. The line in question is converting from the ASCII ordinal value to something in the range 0-25, which allows the used array to store whether each letter of the alphabet has been checked.

65 is ASCII for 'A', but your words are all in lowercase. So instead of (int)mysteryWord.charAt(cl)-65, you should do (int)mysteryWord.charAt(cl)-'a'

change
if (used[(int)mysteryWord.charAt(cl)-65])
guessed.append(mysteryWord.charAt(cl));
else
guessed.append(".");
}
to
if (used[(int)mysteryWord.charAt(cl)-97])
guessed.append(mysteryWord.charAt(cl));
else
guessed.append(".");
}
The code at line 55, when converting to ASCII, is ending up with a value larger than the size of the used array.

Related

What is wrong with the .add in my GUI program?

I am trying to make a GUI with a Grid layout that presents 3 random non repeatable cards within a file. I named all the cards 1-53.png and am trying to insert it into the panels of left, center, and right. When I try adding the files into my panels, there is an error withe the .add, and I do not know how to fix it.
I have already tried to change the .add and the index. I even tried to turn the int into a component, but nothing works.
public class Question_2 {
static String location = "cards/";
public static void main(String[] args) {
JFrame frmMyWindow = new frmMyWindow("Random Cards");
frmMyWindow.setSize(300, 200);
frmMyWindow.setLocationRelativeTo(null);
frmMyWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMyWindow.setVisible(true);
}
}
class frmMyWindow extends JFrame {
JLabel lblName, l;
JPanel panelMain, panelLeft, panelCenter, panelRight;
JFrame f;
public frmMyWindow(String Cards) {
super("Random Cards");
lblName = new JLabel("Cards");
panelMain = new JPanel(new GridLayout(1, 3, 10, 10));
setLayout(new BorderLayout(20, 10));
add(lblName, BorderLayout.NORTH);
add(panelMain, BorderLayout.CENTER);
panelLeft = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 10));
panelCenter = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
panelRight = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 10));
panelMain.add(panelLeft);
panelMain.add(panelCenter);
panelMain.add(panelRight);
panelLeft.setBorder(new TitledBorder("Card 1"));
panelCenter.setBorder(new TitledBorder("Card 2"));
panelRight.setBorder(new TitledBorder("Card 3"));
int index = (int) Math.round(Math.random() * 53);
int index2 = (int) Math.round(Math.random() * 53);
int index3 = (int) Math.round(Math.random() * 53);
while (index == index2) {
index2 = (int) Math.round(Math.random() * 53);
}
while (index3 == index2 || index3 == index)
;
{
index3 = (int) Math.round(Math.random() * 53);
}
String image = index + ".png";
String image2 = index2 + ".png";
String image3 = index3 + ".png";
panelLeft.add(index);
panelCenter.add(index2);
panelRight.add(index3);
}
}
I want the program to present 3 random cards into the panels, but there is an error with the .add.
The problem is indeed to the add method and how you call it. Container#add method takes as arguments Components. You call it with int arguments.
I even tried to turn the int into a component, but nothing works.
The simplest way (I guess) to "add a number in a container" is to create a JLabel and add to it the number as text. By seeing your first attempt, I guess that you again messed up the methods. Probably in JLabels constructor. You did something like new JLabel(index) where index is an Integer. Which again fails because there is no constructor with int argument. The solution is to create a JLabel AND convert the integer to text:
panelLeft.add(new JLabel(String.valueOf(index)));
After that program can be compiled and run. However some notes are:
Always run your application using SwingUtilities#invokeLater since all Swing applications must run on their own thread.
public static void main(String[] args) {
SwingUtilities.invokeLater(()->{
JFrame frmMyWindow = new frmMyWindow("Random Cards");
frmMyWindow.setSize(300, 200);
frmMyWindow.setLocationRelativeTo(null);
frmMyWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMyWindow.setVisible(true);
});
}
All class names "should" (well, its the standard convention) start with an Uppercase letter. Rename frmMyWindow to FrmMyWindow.

change buttons backgroundcolor in awt

So i have a GUI program called Safe25. Basically, if you press the buttons in the right order which is "15032018" the program closes itself.
If you input a correct number, lets say you press 1 at the start, the buttons should change their backgroundcolor to green like this:
If you press a wrong button, the buttons should change their color to red.
But the logic of my code is irrelevant for my problem.
As i said, i want to change the buttons backgroundcolor like in the linked image. My problem is that it changes the backgroundcolor of the frame instead like this
The important line is 75, i commented this one.
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Safe25 extends Frame implements ActionListener {
JButton[] buttons;
Safe25() { // Konstruktor
setSize(250, 300);
setLocation(300, 300);
setTitle("Safe25");
buttons = new JButton[10];
for (int i = 0; i < 10; i++) { // 10 Knöpfe im Array
buttons[i] = new JButton("" + i);
buttons[i].setFont(new Font("Courier", Font.BOLD, 34));
buttons[i].addActionListener(this); //
}
Panel panel0 = new Panel();
panel0.setLayout(new GridLayout(1, 1));
panel0.add(buttons[0]);
Panel panelRest = new Panel();
panelRest.setLayout(new GridLayout(3, 3));
setLayout(new GridLayout(2, 1));
for (int i = 1; i < 10; i++) {
panelRest.add(buttons[i]);
}
add(panel0); // Panel mit 0-Knopf
add(panelRest);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent wv) {
System.exit(0);
}
});
setVisible(true);
}
int s = 0;
public void actionPerformed(ActionEvent evt) {
// 0 1 2 3 4 5 6 7 8 Zustände ...
// 1-5-0-3-2-0-1-8 ist richtige Kombination
switch (Integer.parseInt(evt.getActionCommand())) {
case 0:
s = (s == 2 || s == 5) ? s + 1 : 0;
break;
case 1:
s = (s == 0 || s == 6) ? s + 1 : 1;
break;
case 2:
s = (s == 4) ? s + 1 : 0;
break;
case 3:
s = (s == 3) ? s + 1 : 0;
break;
case 5:
s = (s == 1) ? s + 1 : s == 7 ? 2 : 0;
break;
case 8:
s = (s == 7) ? s + 1 : 0;
break;
default:
s = 0;
}
Color col;
if (s == 0) {
col = Color.red;
} else { // richtiger Weg
col = Color.green;
}
if (s == 8) {
System.exit(0);
}
for (Component c : getComponents()) // line 75, i want this one
c.setBackground(col); // to change the buttons backgroundcolor
repaint(); // but it changes the frames backgroundcolor instead
}
public static void main(String[] args) {
Safe25 we = new Safe25();
}
}
have you red the javadoc for JButton?
edit:
Sorry i looked over your code to quickly. What your doing right now is setting the background color of every component in the current container.
While your buttons array is global you could simply loop trough that collection again to get the correct components "the buttons" and setting the background color like so:
for (JButton b : buttons) // line 75, i want this one
b.setBackground(col); // to change the buttons backgroundcolor
repaint(); // but it changes the frames backgroundcolor instead
The answer is, no, not really - or at least not as you might expect.
The button's content is provided by the look and feel delegate, most of which ignore things like the background property (or at least don't use it in ways you might think it should).
Instead, you need to remove these decorations and do a little of the work yourself
For example...
buttons = new JButton[10];
for (int i = 0; i < 10; i++) { // 10 Knöpfe im Array
buttons[i] = new JButton("" + i);
buttons[i].setFont(new Font("Courier", Font.BOLD, 34));
buttons[i].setContentAreaFilled(false);
buttons[i].setOpaque(true);
buttons[i].setBorder(new EtchedBorder(EtchedBorder.LOWERED));
buttons[i].setBackground(Color.RED);
buttons[i].addActionListener(this); //
}
This disables the area filling, replaces the border and makes the component transparent, which produces something along the lines of

Trying to add label on panel

I am trying to put a label in every single panel I create but I only get the label in the last panel created. Its for a game of snakes and ladders and I am trying to initiate the board for the game. I need every panel to have a number.
public InitBoard() {
JPanel jPanel1 = new JPanel(new GridLayout(10, 10, 0, 0));
JPanel[][] pa = new JPanel[10][10];
//jPanel1.setSize(1024,1080);
int counter=1;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
JPanel tiles = new JPanel();
tiles.setBorder(BorderFactory.createLineBorder(Color.BLACK));
number++;
label1.setText(String.valueOf(number));
tiles.add(label1);
if(counter == 1) {
tiles.setBackground(Color.green);
}
if (counter == 2) {
tiles.setBackground(Color.red);
}
if(counter == 3 ){
tiles.setBackground(Color.cyan);
}
counter++;
pa[i][j] = tiles;
jPanel1.add(pa[i][j]);
if(counter ==5){
counter =1;
}
}
}
add(jPanel1, BorderLayout.CENTER);
setSize(960, 960);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
}
Following image is shown when I run the file.
Any help is appreciated in advance.
I can't see this from the code that you posted, but it seems that you are re-using the same JLabel instance (label1) for all the tiles. This somehow leads to the label being overwritten and re-used for all tiles except the last one.
Just use this line:
tiles.add(new JLabel(String.valueOf(number)));
instead of what you currently have:
label1.setText(String.valueOf(number));
tiles.add(label1);
Making this change, I got your code to work as intended, showing a number on every tile. If the numbers need to be stored somewhere or if you need to be able to change them later, you might want to create an array similar to the one you have for the JPanels (pa).

Java checkerboard, odd/even % 2 panel

I have successfully got a checkerboard to be put together using colored panels, but only when the user will input odd numbers for the rows and columns. Otherwise when inputing even numbers it just shows alternating colored columns. I'm struggling to figure out how to write a short segment that checks to see if it's odd or even by using the %2=0, with the result of even changing the color. Below is my code. Thanks, and take it easy on me I'm very new to programming! :-)
Also, I've created a separate ColorPanel class to build the colored panel, and then pull into into my main program. I didn't bother putting that code below.
import javax.swing.*;
import java.awt.*;
public class Checkerboard extends JPanel{
public static void main(String[] args) {
JFrame chBoard = new JFrame();
chBoard.setTitle("Checkerboard");
chBoard.setSize(800,800);
chBoard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String inputStr = JOptionPane.showInputDialog("Number of rows", "5");
if (inputStr == null) return;
int row = Integer.parseInt(inputStr);
inputStr = JOptionPane.showInputDialog("Number of columns", "5");
if (inputStr == null) return;
int col = Integer.parseInt(inputStr);
Container pane = chBoard.getContentPane();
pane.setLayout(new GridLayout(row, col));
Color BoxColor = Color.red;
for ( int counter = 1; counter <= row * col; counter++ )
{
if (BoxColor == Color.red)
BoxColor = Color.black;
else
BoxColor = Color.red;
ColorPanel panel = new ColorPanel(BoxColor);
pane.add(panel);
}
chBoard.setVisible(true);
}
}
Change your loop to:
for ( int x = 0; x < row; x++ ) {
for(int y = 0; y < col; y++) {
if((x + y)%2 == 0) {
BoxColor = Color.red;
} else {
BoxColor = Color.black;
}
...
}
}
Like I said, I'm new to programming but I'm really enjoying the learning experience. I hope this helps other people in their learning experience.
Anyways, I suppose I created more work for myself with the separate ColorPanel class. So instead of creating a separate ColorPanel class to build the colored panel, I just changed it to use the preexisting JPanel class to create the panel inside the main program. So instead of:
ColorPanel panel = new ColorPanel(BoxColor);
+ the ColorPanel class...
I put:
JPanel panel = new JPanel();
panel.setBackground(BoxColor);
within the main program and deleted the additional ColorPanel class.
Sorry for the redundancy, just wanting to explain myself clearly.
Also, thanks to Jason he really helped me figure out the idea of using the two
int x & y
to count the
row & col
and then add them together which enabled me to use the
%2=0
to figure out whether I was on the odd or even panel.
Hope this helps someone! :-)
Final code looks like this:
import javax.swing.*;
import java.awt.*;
public class Checkerboard extends JPanel{
public static void main(String[] args) {
JFrame chBoard = new JFrame();
chBoard.setTitle("Checkerboard");
chBoard.setSize(800,800);
chBoard.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String inputStr = JOptionPane.showInputDialog("Number of rows", "5");
if (inputStr == null) return;
int row = Integer.parseInt(inputStr);
inputStr = JOptionPane.showInputDialog("Number of columns", "5");
if (inputStr == null) return;
int col = Integer.parseInt(inputStr);
Container pane = chBoard.getContentPane();
pane.setLayout(new GridLayout(row, col));
Color BoxColor = Color.red;
for ( int x = 0; x < row; x++ ) {
for(int y = 0; y < col; y++) {
if((x + y)%2 == 0) {
BoxColor = Color.red;}
else{
BoxColor = Color.black;}
JPanel panel = new JPanel();
panel.setBackground(BoxColor);
pane.add(panel);
}
chBoard.setVisible(true);
}
}
}

Java GUI - Adding text field

I'm not really keen on Java GUI, but am learning as I go. I am in the process of making a very simple and basic Sudoku puzzle. Right now I am just on the basic layout of it.
I wanted to see if there was a simple way of adding a text field to each little rectangle that I have drawn out (81 total rectangles - 9x9 puzzle). So that a user can type something in there.
I am delving into it, but wanted to get the code up here to see if anyone had any tips, cause truth be told, I am mega lost with this.
Here is what I have so far...
import java.awt.*;
import javax.swing.*;
class MyCanvas extends JComponent {
public void paint(Graphics g) {
int coordinateX = 0;
int coordinateY = 0;
// maximum 9 rows
int rows = 9;
int columns = 1;
// make a 9x9 puzzle
while (columns <= rows) {
//for loop to increment the boxes
for (int j = 1; j <= rows; j++) {
// add and assign coordinte x... equivalent to x = x + 30
coordinateX += 30;
// where x and y determine start of the box and 30 determines the size
g.drawRect(coordinateX, coordinateY, 30, 30);
} //end of for loop
//reset the value of x to start a new row
coordinateX = 0;
coordinateY += 30;
columns++;
} //end of while loop
} //end of void paint
} //end of class
public class DrawRect {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(100, 100, 500, 500);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
} // end of void main
} // end of class
Hopefully someone has some pointers that could help me out, cause boy oh boy do I need it. Was kinda thrown into the lion's den without prior knowledge or practice, but I'm trying hard.
Thanks guys!!
You could use a GridLayout(9,9) and an array of arrays of JTextField's
This is, of course, just an example of how I would do it. There are other ways to do this.
Find below a generic example.
Solution
public static void main(String[] args) {
JTextField[][] boxes = new JTextField[9][9];
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(9,9));
frame.setSize(500, 500);
for (int i = 0 ; i < 9 ; i++){
for (int j = 0 ; j < 9 ; j++){
boxes[i][j] = new JTextField("0");
frame.add(boxes[i][j]);
}
}
frame.setVisible(true);
}
Output

Categories

Resources