I have custom class called ButtonList, like a list of buttons, i am adding all the buttons that are going into the window to that 2d array object of button list.
ButtonList[][] buttonList;
buttonList = new ButtonList[5][3];
and I'm constantly getting Null pointer error when im am trying to add the
JButtons to the buttonList.
this.buttonList[column][row].addButton(buttonImage);
ButtonList and addButton method looks like so:
static class ButtonList{
int column = 0;
int row = 0;
JButton[][] arrayButton = new JButton[this.column][this.row];
void addButton(JButton BUTTON){
arrayButton[this.column][this.row] = BUTTON;
System.out.println("Row: " + this.row + " Column: " + this.column);
this.column += 1;
this.row += 1;
System.out.println("button inserted at " + this.row);
}//end addButton
what is it that i am doin wrong?
thanks
int column = 0;
int row = 0;
JButton[][] arrayButton = new JButton[this.column][this.row];
You initialize your array before your constructor get called. So at this point your column and row are still 0. You initialize then an array of [0][0]. This is why later on you get a null pointer exception even though you may have changed the values of row and column in your constructor or later on in any method. But at the time of the creation they were 0.
Moreover
arrayButton[this.column][this.row] = BUTTON;
This is quite probable to give you a out of bounds exception because arrays in java are 0 indexed so your valid range is from [0,column-1][0,row-1] so you may want to fix this as well.
JButton[][] arrayButton = new JButton[this.column][this.row];
this line create an 2d array (without initialization), and infact is equivalent to this:
JButton[][] arrayButton = new JButton[0][0];
0 happens to be the value of the column and row at that time. Changing the value of these two variables does not take any effect on the array it self.
Solution:
If you know in advance the max value of column and row, use that value for array creation. If not, use ArrayList, you will be able to change your size later.
Related
I am trying to give each JButton from a 10 x 10 button layout (so 100 buttons) each unique name or ID or number so I can call them later. I made an ArrayList because that's what some other person did.
public ArrayList<JButton> myList;
//Some other code
for(int row = 0; row < 10; row++)
{
for(int col = 0; col < 10; col++)
{
button = new JButton();
button.addActionListener( al );
myList.add(button);
for(JButton button : myList)
button.setText("");
panel_1.add(button);
}
}
The program compiles but it doesn't run. It's showing error at
myList.add(button);
It's a null pointer exception apparently.
but I don't know why. Is it not adding the buttons to the ArrayList? Also how do I give each button a unique name or string?
The program compiles but it doesn't run. It's showing error at
The ArrayList is null because you didn't create an ArrayList object.
The code should be:
private ArrayList<JButton> myList = new ArrayList<JButton>();
Also how do I give each button a unique name or string?
There is no need to give the button a unique name. Its unique name is the "index" used to access the JButton in the ArrayList.
You probably don't even need the ArrayList.
Normally you add an ActionListener to the button. Then you can just use the getSource() method of the ActionEvent to get the reference to the button.
I would like to create a minesweeper game. Firstly, this will work on buttons. I think I will work on two dimensional array, and there will be like boolean array that will present where are bombs, for example if booleanArray[0][4] is true, there is a bomb.
Now, how can I implement this in my buttons? I can set Names on these buttons, and then if I click some button, then I will get the name from this div. For example when i click first button, i will get "00" name, then i will get first letter "0" and second letter "0" and parse it to int. And this will be the indexes from my previous booleanArray, in this case it will be booleanArray[0][0].
So, can I do this another, better way, instead of that?
This is the way I will be creating the buttons:
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
JButton button = new JButton("");
button.setPreferredSize(new Dimension(50, 50));
button.setName(Integer.toString(i) + Integer.toString(j));
}
}
EDIT
I will have a two dimensional Array, that will reflect my buttons:
and now, how can I check if I hit the bomb after I click for example in the first button?
Just hold a two dimensional array of buttons,
JButton[][] myButtons = new JButton[10][10];
which you use to draw them and they all call the same method with their value
for (int x=0; x<10; x++){
for (int y=0; y<10; y++){
myButtons[x][y] = new JButton("0");
//add to page, or do it elsewhere
myButtons[x][y].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
selectionButtonPressed(x,y);
}
});
}
}
Then a call to yout method selectionButtonPressed() will tell you what button has been pressed, you can take action and even make changes to the button with myButtons[x][y].whatever()
That is one way but you should create the String of the name by using something like:
button.setName(i + ":" j);
This will make it easier to parse out the two values as you can just use the String.split(...) method.
Another option might be to create a HashTable with the JButton as the key and then use a Point object (representing the row/column) as the value Object of the HashTable. Then you just use the get(...) method of the HashMap to retrieve the Point for the clicked button.
Another option is to extend JButton and add two parameters (row, column) when creating the button. Then you also add getRow() and getColumn() methods.
Either of this approaches will keep the logic simple and you only need to create a single ActionListener to be used by all the buttons.
So I have numbered JLabels declared like so (In the class)
OP_1
OP_2
OP_3
etc..
And I have a number and a string.
What I want is that when, for example, the number is 2. I want to change the label text to the content of the string. This is part of a method that is supposed to take a string, put it into the last available JLabel, and then increment the number.
I am very confused, and help would be appreciated.
Here I created an array of JLabels and a method, updateNextLabel(String), which will update the next JLabel with whatever you enter for str.
public class Example {
static int count = 0; //Create a count
static JLabel[] array = new JLabel[3]; //Create an array to hold all three JLabels
public static void main(String[] args) {
//Set the default text for each JLabel
array[0] = new JLabel("This is OP1");
array[1] = new JLabel("This is OP2");
array[2] = new JLabel("This is OP3");
//Here is an example if you wanted to use a for-loop to update the JLabels
for (int x = 0; x < array.length; x++) {
updateNextLabel("This is the new text for OP" + (count + 1));
System.out.println(array[x].getText());
}
}
public static void updateNextLabel(String str) {
array[count].setText(str);
count++;
}
}
Instead of / additional to naming your labels by specific names you can later match them on, I'd think a Map of JLabels with Strings or Integers as keys might be a better approach:
Map<String,JLabel> labelMap = new HashMap<String,JLabel>();
labelMap.put("1", OP_1);
labelMap.put("2", OP_2);
This will allow later access of "The label for key 2" as well as "list me all that labels and find the one with text 2" as well
am trying to fill a JTable form from an existing Object[][][] Array the problem that i all the data or containing the [Ljava.lang.Object;# instead of my (integer) data even though i mad a System.out.println("") to print the data before putting them into the JTable but i always get the same problem ; here is the code next with a small shot screen and thanx for the help.
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
public class gass extends JFrame {
String title[] ={"Box", "Weight", "Priority"};
public gass() {
int nb=interface1.BNumber;
Object[][][] data = new Object[nb][nb][nb];
int E1=0, E2=0;
for (int i=0;i<nb;i++)
{ data[i][0][0] = i+1;
E1 = (int) (Math.random() * 100);
data[0][i][0] = E1;
E2 = (int) (Math.random() * 10);
data[0][0][i] = E2;
}
for (int j=0;j<nb;j++)
{
System.out.println("*"+data[j][0][0]+"*"+data[0][j][0]+"*"+data[0][0][j]+"*");
}
JTable table = new JTable(data, title);
Component add = this.getContentPane().add(new JScrollPane(table));
this.setVisible(true);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
this.setSize(800,400);
}
}
Another problem that i get wrong data always in the first cases of the Object Array ***data[0][0][0] = wrong information !!***
next, a Link for a description of the output of my small application and thanks a lot for the help
Click in this link here to get Description Image
The JTable constructor takes an Object[][] as argument.
This array is an array of rows. So data[i] is a row, which is an array of columns.
And each row in the array is itself an array of columns. Each column (data[i][j]) should contain some data displayed in one cell of the JTable.
In your case, this data is itself an array. Since there is no specific renderer associated to object arrays, the toString() method of your array is used to display the array in the cell. And an array's toString() method returns something like [Ljava.lang.Object;#.
You should tell us what you would like to display in each cell, to get a better answer, explaining what you should do.
EDIT:
given what you want to display, you just need a two-dimensional array:
Object[][] data = new Object[nb][3]; // nb rows, 3 columns
for (int row = 0; row < nb; row++) {
data[row][0] = row + 1; // first column: row number
data[row][1] = Math.random(100); // second column: weight
data[row][2] = Math.random(10): // third column: priority
}
I have a class, "Tetris", in which one of the instance variables is "board". "board" is 2D array of Color objects. Upon the creation of a tetris object I call a method that sets the dimensions of board and then sets all of the Color objects to be the Default value, that is to say, Color.blue.
public Tetris(int rows, int cols) {
this.rows = rows;
this.cols = cols;
reset(rows, cols);
}
public void reset(int rows, int cols) {
Color[][] board = new Color[rows][cols];
for(int i = 0; i<this.rows; i++) {
for(int j = 0; j<this.cols; j++) {
board[i][j] = DEFAULT_COLOR; // Color.blue; //DEFAULT-COLOR
}
}
}
Unfortunately, when I run the code (which obviously has not been posted in its entirety) I get a null pointer exception on the line:
board[i][j] = DEFAULT_COLOR; // Color.blue; //DEFAULT-COLOR.
Is there anything obviously wrong with what I am doing?
It would help if you would post a short but complete program which demonstrated the problem. The code you've posted isn't enough to throw an exception, but I can see how with a few changes it might.
In particular, it seems odd to me that you're declaring a new local variable within your reset method... and you also have an instance variable called board? I suspect the solution may be as simple as changing the start of reset to:
board = new Color[rows][cols];
If your real code uses the local variable to create the array, but then tries to assign values via the instance variable, that could very well be the cause of the problem.
It also seems wrong that you're passing rows and cols into the method, and using those parameters in one place but the instance variables this.rows and this.cols in the loop. Why bother passing them at all?
I think you must allocate every one of those colors like this:
board[i][j] = new Color(...