JScrollPanes empty despite input arrays and DefaultListModels not being empty - java

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();

Related

Modify the dimensions properties of actors collected with libGDX's stack inside a table

In My Code: I created a Table(); contains a many of buttons and labels inside Stack(); (libGDX's Stack).
table = new Table();
table.setFillParent(true);
Stack[][] stackTable = new Stack[LENGHT_TILE][LENGHT_TILE];
Label[][] lbl = new Label[LENGHT_TILE][LENGHT_TILE];
Button[][] btnSquares = new Button[LENGHT_TILE][LENGHT_TILE];
for (int row = 0; row < btnSquares.length; row++) {
for (int col = 0; col < btnSquares[0].length; col++) {
lbl[row][col] = new Label("" + array[row][col], style);
lbl[row][col].setAlignment(Align.center);
lbl[row][col].setTouchable(Touchable.disabled);
btnSquares[row][col] = new Button(new Image(texture).getDrawable());
stackTable[row][col] = new Stack();
stackTable[row][col].add(btnSquares[row][col]);
stackTable[row][col].add(lbl[row][col]);
table.add(stackTable[row][col]);
}
}
stage.addActor(table);
I CAN'T modify the widths, heights, sizes and scales of these buttons or labels. WHY ??
I do not understand what you are doing here. Why would you need to store all those actors in multidimensional arrays? I advice you to start a bit smaller:
Table table = new Table();
Stack stack = new Stack();
TextButton frontButton = new TextButton("Front", skin);
TextButton backButton = new TextButton("Back", skin);
stack.add(backButton);
stack.add(frontButton);
//Now this should work fine
table.add(stack).height(...).expandX(...).fillX().row();
Are you storing your buttons in these actors for later reference? If you want to make somkind of tile system or raster then Table is perfectly capable of making that without all these multi dimensional arrays. So I'm not sure what you are trying to accomplish here but it looks wrong or overly complicated If a Stack, Label and Button are related I'd make a container class for this.
Class MyContainer()
{
Stack stack;
Label label;
Button button;
//Getters & setters
//...
public MyContainer(Stack stack, Label label, Button button)
{
this.stack = stack;
//...
}
}
Now instead of adding in the multidimensional arrays you can add them into a container and add these in a list. You can add listeners for your actors in this class and all is nice and contained.

Java how to create several jlists at runtime

I need to create some tabbedpane called "menu" and in each of them I need to put a Jlist (product) with some other data extracted from a mysql db. I created this method but unfortunately it shows only the last jlist, the others menu tabbedpane are empty. Why? Thanks.
for (int i = 0; i < menuLista.size(); i++) {
int menuId = menuLista.get(i).getMenuId();
jProductList = new JList(modelProductList);
prodottiLista.clear();
modelProductList.clear();
prodottiLista = DBManager.fillProductList(menuId);
for (int b = 0; b < prodottiLista.size(); b++) {
modelProductList.addElement((Product) prodottiLista.get(b));
}
jProductList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jProductList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jProductListValueChanged(evt);
}
});
JPanel pL = new JPanel();
pL.add(jScrollPane3);
// panelList.add(pL);
jTabbedPane1.addTab(menuLista.get(i).getMenuName(), pL);
jScrollPane3.setViewportView(jProductList);
}
I've modified the code like this:
for (int i = 0; i < menuLista.size(); i++) {
int menuId = menuLista.get(i).getMenuId();
modelProductList.clear(); // ricarico la lista dei prodotti.
prodottiLista = DBManager.fillProductList(menuId);
for (int b = 0; b < prodottiLista.size(); b++) {
modelProductList.addElement((Product) prodottiLista.get(b));
}
System.out.println(modelProductList);
JScrollPane scrollPane = new JScrollPane(jProductList);
jTabbedPane1.addTab(menuLista.get(i).getMenuName(), scrollPane);
jProductList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jProductList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jProductListValueChanged(evt);
}
});
}
But It still doesn't work as I expected.
EDITED AGAIN:
I noticed that if I put this line:
System.out.println(modelProductList);
after that block of code, it prints exactly only the last products.
So, it's not a problem of visualization. Any suggestion?
jTabbedPane1.addTab(menuLista.get(i).getMenuName(), pL);
jScrollPane3.setViewportView(jProductList);
You add the last JList created to the viewport of the scroll pane. A viewport can only contain a single component.
I would guess you should be adding the tabbed pane to the viewport of the scroll pane. The tabbed pane should be added to the viewport outside of the loop, after all the tabs have been created.
Edit:
Sorry, I misread your code, I see you are adding the list to the scrollpane to a panel to the tabbed pane, so my suggestion is wrong.
However, I was close (I think?). I believe the problem is now with this line:
pL.add(jScrollPane3);
You only have a single instance of the scroll pane, so it can only be displayed on the last tab.
You need to create a new scroll pane for each tab. I would use code like the following:
JScrollPane scrollPane = new JScrollPane( jProductList );
jTabbedPane1.addTab(menuLista.get(i).getMenuName(), scrollPane);
There is no need to add the scroll pane to the panel first. Now the scrollpane will resize as the size of the tabbed pane resizes.
Also, as a side not you should not be using instance variables in your for loop. Instead you should just be using local variables, since these variables will only exist to help you create the GUI objects you add to the tabbed pane.
For example, jProductList, prodottiLista, modelProductList, should all be local variables and you need to create a new instance of each class. You can't just clear() the contents from the model, because each JList will not have a reference to the same model, so again the data that you add to the last tab will be displayed on all tabs.
Ok, I've resolved. This is the working code:
for (int i = 0; i < menuLista.size(); i++) {
int menuId = menuLista.get(i).getMenuId();
DefaultListModel modelProductList = new DefaultListModel();
JList jProductList = new JList(modelProductList);
prodottiLista = DBManager.fillProductList(menuId);
for (int b = 0; b < prodottiLista.size(); b++) {
modelProductList.addElement((Product) prodottiLista.get(b));
}
JScrollPane scrollPane = new JScrollPane(jProductList);
jTabbedPane1.addTab(menuLista.get(i).getMenuName(), scrollPane);
jProductList.addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
jProductListValueChanged(evt);
}
});
jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jProductList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
}

Why am I getting a NullPointerException in this loop?

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();

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();
}

Categories

Resources