Why am I getting a NullPointerException in this loop? - java

else if(e.getSource()==button3){
JButton[] addSong = new JButton[50];
JLabel[] label = new JLabel[50];
JPanel[] smallPanel = new JPanel[50];
JPanel panel = new JPanel(new GridLayout(1,50));
for(int i=0;i<50;i++){
addSong[i].setText("+");
label[i].setText("Name of song");
smallPanel[i].add(addSong[i]);
smallPanel[i].add(label[i]);
panel.add(smallPanel[i]);
}
tabs.addTab("All Songs",panel);
}
All of the statements in the for loop give me a NullPointerException. I'm new to Java =/

Elements in an Object array are null by default. Initialise the elements of all arrays prior to attempting to invoke any operations on them
for (int i=0; i < 50; i++){
addSong[i] = new JButton();
label[i] = new JLabel();
smallPanel[i] = new JPanel();
...
}

When creating an array of objects, the elements in the array are all initialized to null. You must create the object and assign it to an element in the array before accessing it and calling a method on it.
// Before calling a method on the array position...
label[i] = new JLabel();
// Then you can do this...
label[i].setText("Name of song");
The other arrays will need their elements initialized to actual objects similarly.

else if(e.getSource()==button3){
JButton[] addSong = new JButton[50];
JLabel[] label = new JLabel[50];
JPanel[] smallPanel = new JPanel[50];
JPanel panel = new JPanel(new GridLayout(1,50));
for(int i=0;i<50;i++){
addSong[i] = new JButton("+"); // creates a new button with text "+"
label[i] = new JLabel("Name of song"); // creates a new JLabel with text "Name of song"
smallPanel[i] = new JPanel();
smallPanel[i].add(addSong[i]);
smallPanel[i].add(label[i]);
panel.add(smallPanel[i]);
}
tabs.addTab("All Songs",panel);
}
the reason of this behavior is because by default in an Array of Object (that you created with Type[], where Type is one of JPanel, JButton and JLabel) all records are indeed Objects, but null.
That means that you are telling java "hey, in this array go only this Object", Java knows that only "Object" type can go inside its "spaces" but don't know what kind of objects.
This is the reason why for each "space" in the array (looped with the for cycle) you have to tell Java "here go a new JButton" (or JPanel, or JLabel). And this is the way:
arrayName[index] = new Type();

Related

JScrollPanes empty despite input arrays and DefaultListModels not being empty

Ok, so I'm trying to create two separate JScrollPanes that takes two lists; One list of users and one list of books and simply presents them. The problem is that right now, I have 19 items in my "bookData"-array and 15 in my "userData"-array, but both my JScrollPanes are as empty as my wallet.
When checking my DefaultListModels with getSize(), I see that they too are 15 and 19 in size. I feel like I'm missing something crucial here. The million dollar question is what?
!! - EDIT:
Just noticed the ODDEST behaviour!
My lists aren't empty as such - This is how the window looks on start;
http://i60.tinypic.com/2nr0kyu.png
BUT - and here's the twist! As soon as I change size on the window by dragging the corners - MY LISTS APPEAR! Thus, the error is not in the lists, but in the graphics, methinks. :3
http://i61.tinypic.com/2ah7ac3.png
This is how my method looks;
public void newLoan(){
StringBuilder sb = new StringBuilder();
StringBuilder string = new StringBuilder();
JLabel userLabel;
JLabel bookLabel;
JButton btnRegister;
// Build a string of all users, separated with a "–"
for (int i = 1; i < Processes.userList.size()+1; i++) {
sb.append(Processes.userList.get(i).getFirstname()+" "+Processes.
userList.get(i).getSurname()+", "+Processes.userList.
get(i).getPersonalID()+"–");
System.out.println(Processes.userList.get(i).getFirstname()+" "+Processes.
userList.get(i).getSurname()+", "+Processes.userList.
get(i).getPersonalID());
}
// Build a string of all books, separated with a "–"
for (int i = 1; i < Processes.bookList.size()+1; i++) {
if (Processes.bookList.get(i).getAvailable()-
Processes.bookList.get(i).getOnLoan()!=0) {
string.append(Processes.bookList.get(i).getAvailable()-
Processes.bookList.get(i).getOnLoan()+" available - "+
Processes.bookList.get(i).getTitle()+" by "+Processes.
bookList.get(i).getAuthor_firstname()+" "+Processes.
bookList.get(i).getAuthor_surname()+" ("+Processes.
bookList.get(i).getIsbn()+")–");
System.out.println(Processes.bookList.get(i).getAvailable()-
Processes.bookList.get(i).getOnLoan()+" available - "+
Processes.bookList.get(i).getTitle()+" by "+Processes.
bookList.get(i).getAuthor_firstname()+" "+Processes.
bookList.get(i).getAuthor_surname()+" ("+Processes.
bookList.get(i).getIsbn());
}
}
// split sb at the "–"'s and fill an array.
String[] userData = sb.toString().split("–");
System.out.println(userData.length);
// split string at the "–"'s and fill an array.
String[] bookData = string.toString().split("–");
System.out.println(bookData.length);
/* Defining sizes and locations and initializing all variables. Also
* defining text on buttons and labels.*/
DefaultListModel userModel = new DefaultListModel();
for (int i = 0; i < userData.length; i++) {
userModel.addElement(userData[i]);
}
System.out.println(userModel.getSize());
final JList userJList = new JList();
userJList.setModel(userModel);
JScrollPane userList = new JScrollPane(); //f*cking JScrollPane! Work!
userList.setViewportView(userJList);
DefaultListModel bookModel = new DefaultListModel();
for (int i = 0; i < bookData.length; i++) {
bookModel.addElement(bookData[i]);
}
System.out.println(bookModel.getSize());
final JList bookJList = new JList();
bookJList.setModel(bookModel);
JScrollPane bookList = new JScrollPane();
bookList.setViewportView(bookJList);
userLabel = new JLabel("Select user to register loan onto:");
userLabel.setSize(250,20);
userLabel.setLocation(20, 50);
userList.setSize(150, 200);
userList.setLocation(70, 80);
bookList.setSize(150, 200);
bookList.setLocation(400, 80);
btnRegister = new JButton("Register loan");
btnRegister.setSize(150,50);
btnRegister.setLocation(235, 300);
// Adding functionality... Later
// Adding the different components to the panel "newLoan".
newLoan.add(userLabel);
newLoan.add(userList);
newLoan.add(bookList);
newLoan.add(btnRegister);
}
My first thought was to simply use my String arrays and present them in the JScrollPanes, as such;
final JList userJList = new JList(userData);
JScrollPane userList = new JScrollPane();
userList.setViewportView(userJList);
But that didn't work, obviously.
The solution was extremely complex. Added private DefaultListmodel's outside the method for each of the lists and added everything as elements to those models. And last, but not least I repainted the JPanel using;
newLoan.repaint();

Individually Identifying JButtons in a GridLayout

I have been creating a system by which I am listing various seats on a train within a GUI. I had decided to use a simple grid layout with numbered JButtons representing the seats and the seatNo and empty JLabels to represent empty space (I realise this may be trivial but it was simple). I have used a Gridlayout and I have created the Buttons and Labels as shown below.
I have an List (compArray2) in a separate class that consists of 0s and 1s and a direction that represent where there should be a seat and where the shouldn't be a seat. the .getNum gets the value either 0 for empty space or 1 for a seat and the .getDir gets the direction the seat will be facing.
public JPanel rowPanelCreation(int type, int rowNo, int width){
theNoOfSeats=0;
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(0,width));
List<seatLayout> layout = new ArrayList<>();
layout = ModelConstants.compArray2;
for (seatLayout isit : x2){
buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
buttonDis = new JLabel();
if (isit.getNum()==0){
if (isit.getDir()=='x'){
panel.add(buttonDis);
}
}
else if (isit.getNum()==1){
theNoOfSeats++;
if (isit.getDir()=='N'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultN.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
else if (isit.getDir()=='E'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultE.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
buttonEna.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e){JOptionPane.showMessageDialog(null,"You have chosen : ");}});
panel.add(buttonEna);
}
else if (isit.getDir()=='S'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultS.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
else if (isit.getDir()=='W'){
image = new ImageIcon("/Users/Tomousee/NetBeansProjects/SortedList/src/Resources/chairDefaultW.png");
buttonEna.setIcon(image);
buttonEna.setText(String.valueOf(ModelConstants.compSeatNo.get(theNoOfSeats)));
buttonEna.setHorizontalTextPosition(JButton.CENTER);
buttonEna.setVerticalTextPosition(JButton.CENTER);
panel.add(buttonEna);
}
}
}
return panel;
}
the main problem I am having is that when I press one of the seat buttons I want a message to appear telling me the seatNo of the seat I have selected is. However when I do this it simply displays the very last seatNo. Is there a better way I could do this ? I'm assuming that as all the buttons are fundamentally the same, there is no way to differentiate between them ?
"I want a message to appear telling me the seatNo of the seat I have selected is. However when I do this it simply displays the very last seatNo."
Here's your problem. It's a reference problem. In the end, all the buttons will have the same JButton and JLabel reference. So all the buttons and labels will get the last button and label reference created, hence "displays the very last seatNo."
buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
buttonDis = new JLabel();
You need to create a new JButton and new JLabel reference each iteration
JBUtton buttonEna = new JButton();
buttonEna.setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
JLabel buttonDis = new JLabel();
Another approach would be to have an array of JButton, loop to set the buttons, and add them to the Panel. Say you have a GridLayout(2, 2). You then would need a array of 4 JButtons
JButton[] buttons = new JButton[9];
...
for (int i = 0; i < 4; i++){
buttons[i] = new JButton();
buttons[i].setFont(new Font("Sans Serif", Font.BOLD , 14));
buttonEna.setBorderPainted(false);
// set other properties for button
panel.add(buttons[i]);
}

Java iterate through JList which contains JPanel - JLabel

I am trying to iterate over a JList where each item contains:
JPanel - JLabel
Currently what i have is:
System.out.println("Reading all list items:");
System.out.println("-----------------------");
for (int i = 0; i < menuList.getModel().getSize(); i++) {
Object item = menuList.getModel().getElementAt(i);;
System.out.println("Item = " + item);
}
The output i get is:
Item =
javax.swing.JPanel[,0,0,0x0,invalid,layout=java.awt.FlowLayout,alignmentX=0.0,alignmentY=0.0,border=,flags=9,maximumSize=,minimumSize=,preferredSize=]
Instead i want to access the text that is inside the JPanel.
How could this be done?
Edit:
This is how i add my JPanel to the JList
menuList = new JList(v);
v = new Vector <String> ();
menuList.setListData(v);
.....
// get our images
Icon pingImage = new javax.swing.ImageIcon(getClass().getResource("/resources/icnNew.png"));
// add the images to jlabels with text
JLabel pingLabel = new JLabel("Hi there", pingImage, JLabel.LEFT);
// create the corresponding panels
JPanel pingPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
// add the labels onto the panels
pingPanel.add(pingLabel);
v.add(pingPanel);
So the text i want to find is "Hi there"
Then what you need is to check for the elements inside that JPanel. I mean, a panel is a container of UI elements, that said, you need to check for the elements, once you checked for that you need to compare whether it is a label or not, if it is a label then you will be able to get the text of that label.
Can't you show us the code, probably could be easier if you provide the snippet.

Java - NullPointerException Issue

I have been working on a program and when I run it I get an error that says line 43 and 84 have a NullPointerException. This is the code. I have put comments where line 43 and 84 are. I am trying to make a word processor like Microsoft Word.
import javax.swing.*;
import java.awt.*;
public class Graphics {
// listing all the components
JFrame f1;
JPanel colorspanel;
JPanel sizepanel;
JPanel fontpanel;
JPanel mainpanel;
JTextField Maintextfield;
JLabel colorlabel;
JLabel sizelabel;
JLabel fontlabel;
JButton colorbuttons[];
JButton sizebuttons[];
JButton fontbuttons[];
Graphics() {
// making instances of panels
colorspanel = new JPanel();
sizepanel = new JPanel();
fontpanel = new JPanel();
mainpanel = new JPanel();
// setting the size of the panels
colorspanel.setSize(216, 144);
sizepanel.setSize(216, 144);
fontpanel.setSize(216, 144);
mainpanel.setSize(612, 756);
// making instances of button
colorbuttons = new JButton[9];
sizebuttons = new JButton[14];
fontbuttons = new JButton[9];
// setting content for buttons
// colorbuttons
colorbuttons[0].setBackground(Color.black);//line 43
colorbuttons[1].setBackground(Color.red);
colorbuttons[2].setBackground(Color.blue);
colorbuttons[3].setBackground(Color.yellow);
colorbuttons[4].setBackground(Color.green);
colorbuttons[5].setBackground(Color.gray);
colorbuttons[6].setBackground(Color.DARK_GRAY);
colorbuttons[7].setBackground(Color.ORANGE);
colorbuttons[8].setBackground(Color.pink);
colorbuttons[9].setBackground(Color.magenta);
// sizebuttons
sizebuttons[0].setText("8");
sizebuttons[1].setText("10");
sizebuttons[2].setText("12");
sizebuttons[3].setText("14");
sizebuttons[4].setText("16");
sizebuttons[5].setText("18");
sizebuttons[6].setText("20");
sizebuttons[7].setText("22");
sizebuttons[8].setText("24");
sizebuttons[9].setText("26");
sizebuttons[10].setText("28");
sizebuttons[11].setText("30");
sizebuttons[12].setText("32");
sizebuttons[13].setText("34");
sizebuttons[14].setText("36");
// fontbuttons
fontbuttons[0].setText("New Times Roman");
fontbuttons[1].setText("Blackadder ITC");
fontbuttons[2].setText("Andy");
fontbuttons[3].setText("Buxton Sketch");
fontbuttons[4].setText("Arial Black");
fontbuttons[5].setText("Comic Sans MS");
fontbuttons[6].setText("Old English Text MT");
fontbuttons[7].setText("SketchFlow Print");
fontbuttons[8].setText("Harlow Solid Italic");
fontbuttons[9].setText("Algerian");
f1.setVisible(true);
}
public static void main(String[] args){
Graphics graphics = new Graphics();//line 84
}
}
You allocate a new JButton array, but you don't allocate the elements therein:
colorbuttons = new JButton[9];
There should be a corresponding:
for (int i = 0; i < 9; i++) {
colorbuttons[i]= new JButton(...);
}
Otherwise, you're allocating space for the array of buttons, but never actually initializing each of the JButtons. Thus, colorbuttons[0] is null, and colorbuttons[0].blah() causes the NPE.
You created an array, but you never populated it with anything. You need to put buttons in the array. A NullPointerException means that you tried to reference something, but a null value was found, not an object with a method or property. For example
Object x = null;
x.toString(); // NPE
vs
Object x = new Object();
x.toString(); // we're in business
In your case, you created an array (over 2 lines; just create everything on one line IMHO), but never put the buttons in it. So when you call colorButtons[0].whatever you are trying to access whatever on the reference at index 0. But since you didn't put anything in the array, that reference is null.
Do something more like
JButton[] colorButtons = new JButton[9]; // initialize array
for (int i = 0; i < colorButtons.length; i++) {
JButton button = ... // initialize button each time thru
// do any common setup on the buttons
colorButtons[i] = button; // put the button in the array.
}
You didn't put anything into the colorbuttons array! Of-course it's null.
Here:
for(int i=0; i<colorbuttons.length; i++)
colorbuttons[i] = new JButton();
You JButton array is empty. You just declared it and nothing more.
Populate your array by adding buttons to it.
Something like this:
colorbuttons = new JButton[9];
for (int i = 0; i < 9; i++) {
//Your logic here
colobuttons[i] = new JButton();
}

How to assign dynamically names to a collection of JButton?

I have to create a collection of JButtons depending of a size of a certain collection. How to create the List of JButtons :button1, button2, button3...dynamically to have something like
for (int i=0;i<collection.size();i++){
JButton button+i = new Button();
}
Thanks
Use a list of buttons (or even an array of buttons) :
List<JButton> listOfButtons = new ArrayList<JButton>(collection.size());
for (int i=0; i < collection.size(); i++) {
JButton button = new JButton();
listOfButtons.add(button);
}
Make a List<JButton> and each time through your loop add the new JButton to it.

Categories

Resources