Setting the horizontal alignment of JTextField in a loop - java

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class Excercise24_19 extends JFrame
{
private static int[][] grid = new int[10][10]; //creates a grid
public static void main(String[] args)
{
Excercise24_19 frame = new Excercise24_19(); //creates the frame
frame.setTitle("Excercise 24_19"); //title of window
frame.setLocationRelativeTo(null); //sets location to middle of screen
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true); //displays the window
}
public Excercise24_19()
{
createMatrix(); //creates matrix of numbers inside "grid"
setLayout(new GridLayout(10, 10)); //sets a 10 x 10 layout
String temp; //creates a temp variable to hold number's as string
for(int i = 0; i < grid.length-1; i++)
{
for(int j = 0; j < grid[i].length-1; j++)
{
temp = "" + grid[i][j] + "";
matrix.add(new JTextField(temp, 2));
}
}
}
public static void createMatrix()
{
Random myRand = new Random();
for(int i = 0; i < grid.length-1; i++)
{
for(int j = 0; j < grid.length-1; j++)
{
grid[i][j] = myRand.nextInt(2);
}
}
}
}
PROBLEM: I must create a 10x10 grid with random numbers and use JTextField so that I can change the numbers on the spot. The program must then find the biggest block (Algorithm of O(n^2) complexity) of 1's in the matrix and highlight them red.
Not implemented yet are the listeners or buttons for the other part of this program, and code that finds the largest block of 1's.
My problem is how to i center the text on the JTextFields? Its bothering me because I am not creating variable names for the textfields but I don't see how I am suppossed to center the text inside using ".setHorizontalAlignment(JTextField.CENTER);"
Also will I be able to create listeners for the textfields in case i do change the numbers.
If it helps this is what the end program is suppsed to look like:
This is what my program looks like now:
Thank you in advance for your help!

You have to give the text field a variable name if you want to change its settings. Change this line:
matrix.add(new JTextField(temp, 2));
to these lines:
JTextField text = new JTextField(temp, 2));
text.setHorizontalAlignment(JTextField.CENTER);
matrix.add(text);

Related

Need help creating a simple program to create a matrix based on user input in java swing

The program asks for user input in the terminal: the number of rows and columns. After getting said input it is supposed to generate a matrix using grid layout with the provided numOfRows and numOfColumns.
However, it doesn't really work the way it's supposed to sometimes. For example, an input of numOfRows as 1 & numOfColumns as 5 would not create a matrix with 1 row and 5 columns but instead, it would create one with 1 row and 6 columns.
Below is my code.
import java.awt.*;
import java.io.PrintStream;
import java.text.*;
import java.util.*;
import javax.swing.*;
public class Main extends JFrame {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Enter num of rows for matrix:");
int numOfRow = kb.nextInt();
kb.nextLine();
System.out.println("Enter num of columns for matrix:");
int numOfColumns = kb.nextInt();
kb.nextLine();
JFrame frame = new JFrame();
frame.setLayout(new GridLayout(numOfRow, numOfColumns));
frame.setLocation(0,0);
for(int i=0; i<numOfRow; i++){
frame.add(new TextField());
}
for(int i=0; i<numOfColumns; i++){
frame.add(new TextField());
}
frame.pack();
frame.setVisible(true);
}
}
Any help or insight is genuinely appreciated.
You're adding more text fields than you should. You add 1 row plus 5 columns, that's 6 total. If you want the number of items in a rectangular arrangement, you multiply the width times the depth to get the total.
for(int i=0; i<numOfRow*numOfColumns; i++){
frame.add(new TextField());
}
Delete the other for loop.
Your for loop should be nested, not consecutive:
for (int i = 0; i < numOfRow; i++) {
for (int j = 0; j < numOfColumns; j++) {
frame.add(new TextField());
}
}

ArrayIndexOutOfBoundsException when initializing a 2dimensional array of objectts

I have a very simple question but i can't figure out why I'm having this exception. I'm trying to create a 2-dimensional Array of objects for a sudoku puzzle, but when I'm initializing i'm getting ArrayIndexOutOfBoundsException. Please help, I've read similar questions and it should be working!
Here I'm declaring the grid(2-dimensional array of objects used and constructor):
public class Sudoku extends javax.swing.JFrame {
private int lines;
Cell[][] grid;
public Sudoku() {
initComponents();
grid = new Cell[lines][lines];
So when i'm cliking a button to set the lines(size length) as shown below
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
lines=10;
makeGrid(lines);
}
I'm getting the exception:
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at Sudoku.makeGrid(Sudoku.java:146)
public void makeGrid(int size) {
for(int i=0;i<size;i++)
for(int j=0;j<size;j++) {
146: grid[i][j] = new Cell();
}
}
You should move your grid initialization into the make grid method since in the constructor the member lines is still not initialized with your desired value (default value of int is 0 so you get an empty array and you try to access it afterwards with bigger unallocated bounds)
public void makeGrid(int size) {
this.lines = size; // If you do not need lines anywhere else then it is redundant
grid = new Cell[size][size];
for(int i=0;i<size;i++)
for(int j=0;j<size;j++) {
grid[i][j] = new Cell();
}
}
The problem is that the default value for an int is 0.
So when you create your Sudoku object, grid = new Cell[lines][lines]; is equivalent to grid = new Cell[0][0];
Either change your makeGrid method or provide a size in your constructor.
public void makeGrid(int size) {
this.lines = size;
grid = new Cell[size][size];
for(int i=0;i<size;i++){
for(int j=0;j<size;j++){
grid[i][j] = new Cell();
}
}
}
grid = new Cell[lines][lines]; creates an array of size [0][0] because lines is still 0 when that statement is run.
Whavetever changes you make to lines later on won't affect the array size, which will remain [0][0]...
Simpler example:
int size = 0;
Object[] array = new Object[size];
size = 1;
System.out.println(array.length); //prints 0, not 1
Initialize lines before creation of array. Now you creating array with 0x0 dimensions, because lines is 0 be default.
lines = 10; // Add this line
grid = new Cell[lines][lines];

How to add JButtons to a specific location in a gridlayout, inside a loop?

I am trying to add JButtons to the specified location on a gridlayout but I am not sure how to do this, right now I have
public void addButtons()
{
myBoard = myController.getMyBoard();
for (int i = 0; i < this.getEntryInt(); i++)
{
for(int j = 0 ; j < this.getEntryInt(); j++)
{
if(myBoard[i][j]==true)
{
buttons[i][j] = new JButton("Q"); // error: The type of the expression must be an array type but it resolved to JButton
}
}
}
}
Is there a way to add buttons to a specific plot in the grid layout?
You can't choose where you put components in a GridLayout. They will be added consecutively.
Try using a GridBagLayout instead.

Java out of bounds exception inside nested for loop

this may be an easy one, but I'm getting an out of bounds exception and I'm not sure how to fix it.
Basically, I am trying to create a "table" of integer fields so that I can use them to find if all of the values in the integer fields create a magic square. The nested for loop should create up to an 8x8 square, and it will create the first row of the square, but instead it gives me an out of bounds error.
The error occurs inside of the nested for loop where I'm adding the IntegerField to the GUI.
If anyone can help, that would be great. Let me know if you need more details.
import javax.swing.*;
import BreezySwing.*;
public class Interface extends GBFrame{
//Create integerField array to create input for magic square
public IntegerField[][] magicSquare;
//Create input button, integer field which sets size of square
public IntegerField squareSize;
public JButton inputSize;
//Create check square button
public JButton checkSquare;
//Label to output if there is a magic square
public JLabel squareLabel;
//Size of square variable
public int size;
//CalcSquare object
CalcSquare calc = new CalcSquare();
//Constructor for Square interface
public Interface()
{
squareSize = addIntegerField (0, 1, 1, 1, 1);
inputSize = addButton ("Input Size", 2, 1, 1, 1);
squareLabel = addLabel ("", 3, 1, 1, 1);
checkSquare = addButton ("Check Square", 4, 1, 1, 1);
}
//Creates IntegerFields on the GUI as needed.
public void createFields()
{
for (int i = 0; i <= size; i++)
{
for (int x = 0; x <= size; x++)
{
magicSquare = new IntegerField[i][x];
}
}
}
public void buttonClicked(JButton buttonObj)
{
if (buttonObj == inputSize)
{
size = squareSize.getNumber();
createFields();
for (int i = 0; i <= size; i++)
{
for (int x = 0; x <= size; x++)
{
magicSquare[i][x] = addIntegerField (0, i+1, x+1, 1, 1);
}
}
}
else if (buttonObj == checkSquare)
{
}
}
}
A for loop condition of i <= size Should always raise red flags since if i == size, you've gone beyond the size of the array or collection. Note that arrays and collections are 0 based and go from 0 to size - 1.
It should instead almost always be i < size
All your loops are iterating upto size which will cause ArrayIndexOutOfBoundException. The Array index starts from 0 to size-1. Here is one of such loop in your code:
for (int i = 0; i <= size; i++)
you need to iterate the loop only till size
for (int i = 0; i < size; i++)
Correct other loops accordingly
size is never initialized. And your <= should be < in the for loops.
In fact, if you're using size as a constant to set the size of your arrays, you should use i < size - 1 in for loops.

java nested for() loop throws ArrayIndexOutOfBoundsException

I'm working through a JPanel exercise in a Java book. I'm tasked with creating a 5x4 grid using GridLayout.
When I loop through the container to add panels and buttons, the first add() throws the OOB exception. What am I doing wrong?
package mineField;
import java.awt.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class MineField extends JFrame {
private final int WIDTH = 250;
private final int HEIGHT = 120;
private final int MAX_ROWS = 5;
private final int MAX_COLUMNS = 4;
public MineField() {
super("Minefield");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container mineFieldGrid = getContentPane();
mineFieldGrid.setLayout(new GridLayout(MAX_ROWS, MAX_COLUMNS));
// loop through arrays, add panels, then add buttons to panels.
for (int i = 0; i < MAX_ROWS; i++) {
JPanel[] rows = new JPanel[i];
mineFieldGrid.add(rows[i], rows[i].getName());
rows[i].setBackground(Color.blue);
for (int j = 0; j < MAX_COLUMNS; j++) {
JButton[] buttons = new JButton[i];
rows[i].add(buttons[j], buttons[j].getName());
}
}
mineFieldGrid.setSize(WIDTH, HEIGHT);
mineFieldGrid.setVisible(true);
}
public int setRandomBomb(Container con)
{
int bombID;
bombID = (int) (Math.random() * con.getComponentCount());
return bombID;
}
/**
* #param args
*/
public static void main(String[] args) {
//int randomBomb;
//JButton bombLocation;
MineField minePanel = new MineField();
//minePanel[randomBomb] = minePanel.setRandomBomb(minePanel);
}
}
I'm sure I'm over-engineering a simple nested for loop. Since I'm new to Java, please be kind. I'm sure I'll return the favor some day.
JPanel[] rows = new JPanel[i];
i is 0 in the first iteration, which isn't what you want. Make that:
JPanel[] rows = new JPanel[MAX_ROWS];
Also, I think you want to take that completely outside the for loop, since you seem to be using its elements, which would be uninitialised...
This is also wrong:
JButton[] buttons = new JButton[i];
i can be 0 when j is 2 for example, in which case there's no such thing as a buttons[j]. Make them all MAX_* and I think you want to take them out of the loop, since I don't see the point in recreating them at every iteration. Also, you need to instantiate the individual array elements as well.
This part doesn't really make sense:
for (int j = 0; j < MAX_COLUMNS; j++) {
JButton[] buttons = new JButton[i];
rows[i].add(buttons[j], buttons[j].getName());
}
You're creating an array of i JButtons, and trying to add the jth to rows, which makes little sense and won't work if j >= i. You probably meant to do:
JButton[] buttons = new JButton[MAX_COLUMNS];
for (int j = 0; j < MAX_COLUMNS; j++) {
rows[i].add(buttons[j], buttons[j].getName());
}
But the array still doesn't contain any buttons, all you did is initialize it. There's really no reason for the array at all; this actually works:
for (int j = 0; j < MAX_COLUMNS; j++) {
JButton button = new JButton("foo");
rows[i].add(button, button.getName());
}
JPanel[] rows = new JPanel[i];
When i is 0, you create an array with 0 elements. You then try to access that array, but it has no elements in it.
The problem is that your button array is of size i, but j can be larger than i. For instance, the first time through, you are making an empty array here:
JButton[] buttons = new JButton[i];
because i is equal to 0. You then attempt to access it at index 0, which doesn't exist (since the array has no size) and you get your exception. Should you instead be doing something like:
JButton[] buttons = new JButton[MAX_COLUMNS];
That way you will have a button for each array location. Also, you will probably need to initialize the individual buttons - i.e. something like this:
for (int k = 0; k < MAX_COLUMNS; k++) {
buttons[k] = new JButton();
}
(disclaimer: code not tested, but pulled out of you-know-where for example purposes only. There could be typos or unseen bugs.)
Good luck.
It looks like you're creating way too many arrays. You're creating your arrays INSIDE the loops, so instead of creating 5 rows, you're creating 5 rows 5 times, or 25 rows.
The other problem is that you aren't actually creating any objects, only the array to hold the objects. For each object in your array, you need another "button[j] = new JButton()" line.

Categories

Resources