Accessing elements of an object in a jList/listModel - java

I'm trying to populate a jList, I want it to display a name but also store an ID (which is not displayed) for each item in the list.
I have created a list model and added each element as an object. The object holds an int value (the ID) and a string value (the name):
doorListModel.addElement(nextDoor);
Once all the elements have been added I then send this model to the jList:
jList1.setModel(doorListModel);
When you run the program the jList appears to just show a memory location for each element:
How can I get the jList to just display the String value and, (assuming this is possible) how do I access the hidden int value if I was to select an item from the jList.
Cheers.

You've got two options as I see it:
You can give your Door class a decent toString() method since this is what the JList displays by default, or
Give your JList a decent ListCellRenderer. This is the recommended solution since a toString() result really shouldn't be used for production purposes but rather for debugging.

Related

JTable and its Relationship with the Data Source

I'm building a program that gathers a couple lists of files that match a particular set of criteria and manipulates them as it appropriate depending on the source, type of file, etc... My hope is that it will find the files and display them in a list that is easy to read. The user will select which files are going to be processed from the list, then hit a button that "starts the commotion," if you will.
Right now, I've made a class called DrawingFile that looks like:
class DrawingFile {
private static String fileName, fileType;
private static boolean actionable;
private static Path filePath;
public DrawingFile (Path path){
setFilePath(path);
setFileName(stripExtension(path));
setFileType(getExtension(path));
setActionable(true);
}
...(methods omitted to save time)...
My plan, initially was to create a JTable that populates based on a List of DrawingFiles with each of the fields in the objects being a column in the table, except the Path, which would not be displayed on the table. From there, the user would click a checkbox which would determine whether or not a file is going to be manipulated.
My issues stem first and foremost from my being relatively new to programming. This is the first program I've written that people are going to use, that also has any sort of UI.
As such my questions are:
Does my plan above make any sense at all?
Would it make more sense to leave the table out of it and create a series of JPanels inside a container? (this seems like it wouldn't be best practice)
If I do go with the table, should I scrap the DrawingFile class and store the data in the TableModel?
3a. If so, is there a way I can hide the Path in the table?
How do I go about changing the actionable boolean when it is (un)checked on the table?
On a scale of 1-10, how badly am I overthinking this?
If I understand correctly, you have a list of DrawingFile objects, and want to display this list as a JTable, where each row represents an object of the list. Yes, that makes perfect sense.
No. A table is perfect for that.
No. You should create a custom DrawingFileTableModel class, extending AsbtractTableModel, and using the list of objects as the source to implement the method. Google for "Java tutorial JTable", and you'll find an example in the official tutorial.
By making sure that isCellEditable() returns true for that column and row, and by implementing the setValueAt() and getColumnClass() methods correctly. The javadoc and the tutorial are your friends here. setValueAt(), when called with the index of the boolean column, should set its new value in the DrawingFile stored at the given row index in the backing list. getColumnClass(), when called with the index of the boolean column, should return Boolean.class.

Object to ArrayList to JList and back again (A few questions)

Program Outline:
I plan to make a simple Java program that will load Vehicle objects (Vehicle being the superclass, EnginedVehicle and GoodsVehicle being the subclasses) from an XML file into an ArrayList which will then be displayed on a JList. The user will be able to show/hide the different Vehicle types using check boxes, add a new vehicle type or press the selected item in the JList and edit or delete it. The program will then put the Objects back into the ArrayList where it can be then saved back to the XML file.
Question: So, I am completely fine with the loading of the XML file into the ArrayList and putting that object onto the JList but the thing that is hurting my head is thinking about how I am going to:
What is the best way of getting the object back from the JList ready for it to be modified or deleted and put back into the ArrayList?
How would I show/hide the different types of Vehicles in the JList using the check boxes?
I understand this may seem a lot but, this is my first post and I am new to the community and I have fairly good knowledge of Java and OOP programming but I have just finished writing a fairly big website and going back to Java is a headache.
Since your ArrayList should be equal in size (item count) to your JList, your JList will have the index you're interested based on selection. Regardless if you want to modify or delete the item, store what index it was at and remove the item from the JList (You should be using a DefaultListModel). Use this index value to get the object from your ArrayList. If you're modifying, modify your object as needed, you shouldn't have to remove the object from the ArrayList for modifications, and place it back into your DefaultListModel. If it's a delete, then just remove the object from your ArrayList using the index value you stored.
As far as displaying (show/hide), clear your DefaultListModel (which will clear your JList), iterate through your ArrayList and add the items to the DefaultListModel that match your checkbox selection criteria.
EDIT:
I didn't take into consideration of possibly modifying/deleting items when items are hidden. For this, may want your objects to have a field that stores what index they are at in the ArrayList. This way when you do your filter, I would copy the items from your "Master" ArrayList into a sub list that you can populate your DefaultListModel. Then you apply the same logic to this sublist when selecting an item from you JList, then take your changes from your sublist and apply them to the "Master" ArrayList.
Keep in mind that when you remove an item, you'll have to reassign all items index location from that point on down.
I'm sure there is probably a cleaner way of doing this, but this is what first comes to mind for me.
I don't know if I'm horribly mistaken, but why change to a JList at all? Do you use your JList as a parameter to visualize the information in it? If yes, why dont you use your ArrayList instead? Then the checkboxes only change the visibility ot the Items of the List. So you dont have to care about indices, because they stay the same. And new entries, can be made as well... maybe im wrong but i guess you got kind of a GUI for the user to browse/alter/add new vehicles?

How can I accept a value to be passed, using a method

I am trying to select an item from the jList in one form (Home), and extract the data from the ArrayList and output the data to separate jTextFields in a different form (Details). Below is the method I'm trying to use to do this (not a lot there I know!).
public void passObjectData()
{
int i = proObjList.getSelectedIndex();
}
I know once the method is complete, I can just call it on the form load method in the next form, but I'm stuck on how to get the method correct.
I don't know what other code, if any, will be needed for your help.
I have hardcoded data into an ArrayList and have output a name to a jList. Now I want to get all of the data of one person that is stored
in the ArrayList (name, address, tel num etc) and put this information
into jTextFields.
As I understand your question this ArrayList is the undelying data structure used to fill the ListModel and you want to get the selected index from the JList to retrieve the correct object stored in that array list. In this case you can:
Have a domain class called Person to hold the person's data (name, address, etc)
Add Person objects to the ListModel.
Provide an appropriate ListCellRenderer to display the person's name.
Use JList#getSelectedValue() to get the selected Person.
Pass this selected Person object to the text field's form and update those accordingly.
Optional: attach a ListSelectionListener to the JList in order to listen for user's selection changes and do the previous step automatically.
See the first 3 points of this approach exemplified here (note: the example is using JComboBox but the same applies to JList as well).
Suggested readings
Creating a Model
Selecting Items in a List
Writing a Custom Renderer
Side note
Not sure if by forms you mean JFrames but just in case: please note that we should avoid using multiple JFrames. See this topic: The Use of Multiple JFrames, Good/Bad Practice?

Custom component for JList instead of just strings

I've been trying to freshen up on my Java knowledge and I've been building a small GUI program and I've been running into a bit of a problem.
Basically, I have a JList which I'm currently populating with strings from an object from one of my classes which implement AbstractListModel which we can call my ItemList class. It contains an ArrayList of objects of the type Item which implements Serializable.
But, what I'd like to do is rather than populate my JList with a bunch of strings I'd like to populate it with some kind of string + JTextField combination so I can see one property of each Item object while also being able to update another property by changing the JTextField.
Now, what I'm looking for is the simplest possible way of doing this, and I am assuming there is a (relatively) simple way to do this since it's such a common thing to want to do in a GUI application (although I wouldn't put it past Java and Swing to make it convoluted and complicated).
So, what is the correct way of doing this?
No need to ever use String objects. Instead:
Put Item objects in the JList.
Add a ListCellRenderer to the list, to show the Item object the most user friendly way.
When the user selects an item, show the details in a different place (I'm thinking a panel with 2 columns of labels and text fields, and two rows - one for each attribute, and perhaps a button to Save)
The edit controls would best be encapsulated in a panel that can then hidden when not required, & put in a variety of places, e.g.
Below the list
In the main part of the GUI
displayed in a JOptionPane or a (modal or not) JDialog
Here is an example of placing the 'view/edit panel' (the file details) below the selection component (the table).

how to create a Custom list model in Java

I'm trying to create list that shows contacts, each list item shows the name on a line, and the phone number on a second line, and maybe an image or icon. I was thinking of using two labels for that, but i can figure out how to use a custom list model to implement this.
My first attempt was to add a Panel object that contained the info i wanted in the list, then add it to an instance of the defualt list model, but that only turned up the class name in the list.
DefaultListModel Clistmodel = new DefaultListModel();//
Clistmodel.addElement(Contact);//Contact is an JPanel object
GroupList.setModel(Clistmodel);//GroupList is the List object
this didn't work out at all then i learnt that the default list model only knows how to render strings i think, so i have to create a custom list model, or a custom ListCellRenderer, i don't really know which will solve the problem.
Your question asks how to create a custom list model, however, that's not what you need (I don't think) as a DefaultListModel will work nicely for you. Rather you will need to work on the renderer. You need to create a non-GUI class to hold your information that each item will display, probably your Contact class, and then create a JList that holds this in its DefaultListModel.
The key for you will be to then create a custom list cell renderer to display the information on multiple lines -- perhaps a JTextArea, or a JPanel that holds two JLabels in a GridLayout. Please understand that the renderer does not display the actual underlying components, but something more akin to a stamped image of whatever components you're trying to display, so it will not have the full behaviors available to it as the actual component would. It will take work, but the writing a renderer section of the tutorial linked to by user714965 will show you how to do this.
Please give it a try, and then if you still are stuck, come on back with your code, your errors, and your questions, and we'll be better able to give you specific help.

Categories