java array of arraylists - java

I have four columns of buttons in my program. Buttons move between columns when assigned new ones. Instead of declaring 4 separate arraylists to store the buttons, is there a way to create 1 array of arraylists so I can simply itterate through the array?
I've tried List<JButton>[] lists = new ArrayList<JButton>[5];
But that won't work. What am I missing?
EDIT:
for(int i = 0; i < 5; i++){
if(choiceList.getSelectedIndex() == i){
if(btnPersons[nameList.getSelectedIndex()].getX() == column[i]){
JOptionPane.showMessageDialog(null, "Error - Name already present in the column.","", 1);
}else{
for(int j = 0; j < 5; j++){
if(lists[j].get(i) != null){
lists[j].remove(btnPersons[nameList.getSelectedIndex()]);
}
}
lists[i].add(btnPersons[nameList.getSelectedIndex()]);
lists[i].get(i).setBounds(column[i], ROWS[i], 125, 20);
//reloadLocations();
}
}
}
This is my code currently.Once a new column is selected it checks to see which listthe button was in and removes it, then adds it to the new list. But my new problem is that using lists[i] will no longer work. Idk how to properly loop through my list of arraylists using this declaration:
List<ArrayList<JButton>> lists = new ArrayList<ArrayList<JButton>>();

You have to keep a list of lists of JButton objects:
List<List<JButton>> lists = new ArrayList<List<JButton>>();
// populate (replace with your code)
lists.add(Arrays.asList(new JButton("list 1, button 1"), new JButton("list 1, button 2")));
lists.add(Arrays.asList(new JButton("list 2, button 3"), new JButton("list 2, button 4")));
lists.add(Arrays.asList(new JButton("list 3, button 5"), new JButton("list 3, button 6")));
lists.add(Arrays.asList(new JButton("list 4, button 7"), new JButton("list 4, button 8")));
// iterate
for(List<JButton> subList : lists) {
for(JButton button : subList) {
System.out.println(button.getText());
}
}

Giving an example of what worked for me / talked above.
List []oArrayOfArrayList = new ArrayList[2];
List<String> oStringList = new ArrayList<String>();
List<Integer> oIntegerList = new ArrayList<Integer>();
oArrayOfArrayList[0] = oStringList ;
oArrayOfArrayList[1] = oIntegerList ;

You cannot create arrays from classes with generic parameters.
You'll either want to make a list of a list, or forgo generic parameters.

You are not able to call the new operator for a generic object because at run time the type has been erased.

create a class for your ArrayList:
private class xxx extends ArrayList<JButton> {
// need serial to keep IDE happy
private static final long serialVersionUID = -2392107594926751233L;
};
private xxx[] lists = new xxx[5];

Related

Java: Array list of objects & getting values/properties of automatically created checkboxes

I have a ArrayList of Strings that automatically generates a list of check-boxes (of varying count) in a popup window. I currently have two problems with the below code:
Object[] params doesn't work because it requires me to know the size of the ArrayList ar in advance, and I havent figured out to get an arraylist of objects to work with my code. How can I fix this? I tried creating an arraylist of objects, but I could only get it to display nonsensical text.
How can I get the values/text of each checkbox and it's respective isSelected() state?
Below is my code:
String message = "The selected servers will be shutdown.";
Object[] params = {message, null, null, null, null, null};
ArrayList<String> ar = GetSet.getStopCommand(); // Example array: ./Stopplm11.sh|./Stopplm12.sh|./Stopplm14.sh|./Stopplm15.sh
for(int i=0; i< ar.size(); i++){
JCheckBox checkbox = new JCheckBox();
checkbox.setText(ar.get(i).toString());
checkbox.setSelected(true);
params[i+1]= checkbox;
}
int n = JOptionPane.showConfirmDialog(btnShutdownServer, params, "Shutdown Servers", JOptionPane.OK_CANCEL_OPTION);
if (n == JOptionPane.OK_OPTION){
// DO STUFF
//boolean buttonIsSelected= checkbox.isSelected();
}else{
// user cancelled
}
An image, for those who like images:
You can make it an ArrayList of JCheckBox:
ArrayList<JCheckBox> checkboxes = new ArrayList<JCheckBox>();
Then you can do:
for(int i = 0; i < ar.size(); i++)
{
JCheckBox checkbox = new JCheckBox();
checkbox.setText(ar.get(i).toString());
checkbox.setSelected(true);
// add the checkbox to the ArrayList
checkboxes.add(checkbox);
}
Finally, to check the state of all checkboxes in your if condition, you can simply do:
if (n == JOptionPane.OK_OPTION){
// DO STUFF
//boolean buttonIsSelected= checkbox.isSelected();
// loop through all checkboxes in the ArrayList
for (JCheckBox checkbox : checkboxes)
{
// current one is selected
boolean buttonIsSelected = checkbox.isSelected();
}
// rest of code in if condition
}
Instead of storing params inside of an array, store those parameters within an ArrayList, as such:
ArrayList<Object> params = new ArrayList<Object>();
params.add("The selected servers will be shutdown.");
for(int i = 0; i < ar.size(); i++)
{
JCheckBox checkbox = new JCheckBox();
checkbox.setText(ar.get(i).toString());
checkbox.setSelected(true);
params.add(checkbox);
}
Then, make params an array:
Object[] realParams = new Object(params.size());
realParams = params.toArray(realParams);
And then continue the rest of the code as you would.

I need to make a reference to a JLabel based off a string

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

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

List of List of Buttons is empty

I'm working around with GWT.
Since I have a SQL db and my queries result set size is unknown I thought it would make sense to use Lists.
Actually I have one list of buttons and a second list of list of buttons.
The reason is because I have one table which stores groups and one which stores the actual data. Both of them in result should be buttons.
By clicking on a group button my layout is filled with the data buttons between the group buttons.
Now my db connection isn't ready to use so I wrote a function that fills my lists with fake data. Same for the groups.
public void fakeGroupData () {
// Group index 0
btnGroupList.add(new Button("Group a"));
// Group index 1
btnGroupList.add(new Button("Group b"));
...
}
public void fakeData () {
// Group index 0
btnDataList.add(new Button("Data 1.1"));
btnDataList.add(new Button("Data 1.2"));
btnDataList.add(new Button("Data 1.3"));
btnDataListList.add(btnDataList);
btnDataList.clear();
// Group index 1
btnDataList.add(...
}
Declaration looks like this
List<Button> btnGroupList = new ArrayList<Button>();
List<List<Button>> btnDataListList = new ArrayList<List<Button>>();
List<Button> btnDataList = new ArrayList<Button>();
When trying to get the ButtonList of the ListList the error appears.
int grpIndex = Panel.getWidgetIndex(grpBtn);
// grpBtn is equal to (Button)event.getSource() called by btnGroup ClickHandler
btnDataList.clear()
btnDataList = btnDataListList.get(grpIndex);
int loopEnd = btnDataList.size() - 1;
for (int i = 0; i<=loopEnd; i++) {...
"loopEnd" contains "-1" and nothing happens :(. I tried to debug here, everything seems ok.
"grpIndex" has the right index so the the right List is loaded.
But why is it empty? When debuggin the fakeData function eclipse shows the right size in the ButtonList.
Hope you can help me :)
btnDataList.clear(); will empty your referenced list objects.
for each Group index you need a new list. do like this
btnDataList = new ArrayList<Button>(); instead of btnDataList.clear();
// Group index 0
btnDataList.add(new Button("Data 1.1"));
btnDataList.add(new Button("Data 1.2"));
btnDataListList.add(btnDataList);
// Group index 1
btnDataList = new ArrayList<Button>();
btnDataList.add(new Button("Data 2.1"));
btnDataList.add(new Button("Data 2.2"));
btnDataListList.add(btnDataList);

Consultation about dynamically add to array

how to add unknow numbers of colors to this array ? for example i whant to add 6 colors
int[] colors = new int[] { Color.RED, Color.YELLOW, Color.BLUE,Color.GREEN };
and how to add unknow numbers of categorySeries ? for example i want to add 6 categorySeries
CategorySeries categorySeries = new CategorySeries("Vehicles Chart");
categorySeries.add("cars ", 30);
categorySeries.add("trucks", 20);
categorySeries.add("bikes ", 60);
categorySeries.add("plan ", 40);
thanks in advance
You can't add unknown numbers of items to an array, because arrays can't resize.
Use an ArrayList instead:
List<CategorySeries> categorySeriess = new ArrayList<CategorySeries>();
CategorySeries categorySeries = new CategorySeries("Vehicles Chart");
categorySeries.add("cars ", 30);
categorySeries.add("trucks", 20);
categorySeries.add("bikes ", 60);
categorySeries.add("plan ", 40);
categorySeriess.add(categorySeries);
And for the colors:
List<Integer> colors = new ArrayList<Integer>();
colors.add(Color.RED); // single add
colors.addAll(Arrays.asList(Color.YELLOW, Color.BLUE, Color.GREEN)); // bulk add
Consider using ArrayList, using it's add method and then calling toArray on it. This should work.
If you don't know how many items you want to keep track of, an array is probably not the best choice of data structure. I would recommend a linked list.
Check out java.util.LinkedList. You can use generic types to specify which kind of elements it should hold.
For example,
import java.util.LinkedList;
public class Test {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<Integer>();
ll.push(1);
ll.push(2);
}
}
Alternatively, you could make the CategorySeries linked list with LinkedList<CategorySeries> ll = new LinkedList<CategorySeries>().

Categories

Resources