How to dynamically add items to a JList? - java

I'm having trouble adding items to a JList called lstContacts whenever a button is pressed.
When I press my new contact button, a line should be added to lstContacts but when I press the button nothing happens.
Here is my action listener for the new contact button:
newContactButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Contacts contacts = new Contacts();
contacts.createContact();
}
});
Here is my createContact method in the contacts class:
ArrayList<String> contactsList = new ArrayList<String>();
public void createContact() {
ContactsDB database = new ContactsDB();
System.out.println("new contact");
contactsList.add("New Contact");
listModel.addElement("New Contact");
}
And lastly here is my createCustomUIComponent() method:
private void createUIComponents() {
// TODO: place custom component creation code here
listModel = new DefaultListModel();
lstContacts = new JList<String>(listModel);
}
Why aren't the new contacts getting added to my JList?

The problem is here:
Contacts contacts = new Contacts();
contacts.createContact();
You are creating a new contacts object every time you click the button, but the JList doesn't have a reference to the Contacts object. I don't know how the contacts object is defined, but you should make sure that the object you are adding the contact to has reference to the DefaultListModel.
Another problem I see (but isn't causing the problem you posted about) is that you call new DefaultListModel(), but list model is a parameterized type. You probably want to call new DefaultListModel<String>().

Don't create an ArrayList of Contacts. All the Contact data should be stored in the ListModel.
So when you click on the button all you do is create a Contact and add the Contact to the DefaultListModel. However, your code doesn't make much sense because you're just creating an empty Contact. I would expect the Contact to have a name or something. So really what you want to do is have a text field were the user can enter a name and then when you click the button you create a Contact using the name data and then add the Contact to the list.
Read the section from the Swing tutorial on How to Use Lists. The ListDemo example show you how to dynamically add/remove an item from the DefaultListModel. Download the example and modify the working example to meet your specific requirements. When learning a new concept, start with working code.

First of all you have to have new a default ListView:
DefaultListModel listModel = new DefaultListModel();
Thenm build your JList with this list:
JList jList = new JList(listModel);
Anytime you want to change your list for each action you considered, call
addElement on your jList:
listModel.addElement("This is a test contact");

Related

JavaFX Combo Box Seeing Instances of warehouses

I have a controller that has a combobox defined as so:
private ComboBox warehouseComboBox;
and a method that populates that combobox in that controller
#FXML
void createWarehouseInstance (ActionEvent event){
ArrayList<BikePart> inventory = new ArrayList<>(); //empty inventory
String whName = warehouseNameField.getText();
warehouse wh = new warehouse(whName, inventory); //create new instance
warehouseComboBox.getItems().add(wh);
warehouseArrayList.add(wh); //add instance to arrayList
warehouseNameField.clear(); //clear text box
}
What I'm trying to do is get the state of that combobox and that determines which instance of a class I would be manipulating.
My attempt is so with this method. Where I show a list of Bicycle parts depending on the instance selected with the combo box.
#FXML
void showParts(){
bikePartList.clear();
bikePartList.appendText("Name\tNumber\tListPrice\tSalePrice\tQuantity\tOnSale?\n");
Object selection = warehouseComboBox.getSelectionModel().getSelectedItem();
if (warehouseArrayList.contains(selection)){
bikePartList.appendText(warehouse.printAll()); //what do I do here?
}
}
For context, Warehouses hold BikeParts, and I'm figuring out that if I want to dynamically create warehouses, I can't make this static
If I understand what you're trying to do:
First declare your ComboBox with the proper type:
private ComboBox<Warehouse> warehouseComboBox;
and then you can do
#FXML
void showParts(){
bikePartList.clear();
bikePartList.appendText("Name\tNumber\tListPrice\tSalePrice\tQuantity\tOnSale?\n");
Warehouse selectedWarehouse = warehouseComboBox.getSelectionModel().getSelectedItem();
// I think this is what you're trying to do:
bikePartList.appendText(selectedWarehouse.printAll()); //what do I do here?
}
Note that I changed your class name to conform to standard naming conventions.

Binding String ArrayList to JList

I have created a client -> server chat room system, and I have a list of currently connected users, which is currently displayed on a button click within a JTextField, this currently works fine and displays the string array. However, I have added another component to my GUI, being a JList. I have been trying to create a method called updateUserList to update the JList with the users that are connected. I have tried to use a DefaultListModel of type String, however this displays nothing in the JList and I am unsure as to why.
Below is the updateUserList method I have created:
public void updateUserList()
{
model = new DefaultListModel<String>();
for(String usernames : users)
model.addElement(usernames);
jl_users = new JList<String>(model);
}
Please note that model, usernames and jl_users are defined globally, therefore I have not included them in the post.
Why are you using DefaultListModel?
If you want a simply List just use it like this
public void updateUserList()
{
jl_users = new JList<String>(users.toArray(new String[users.size()]));
}
or straight forward
jl_users = new JList(users.toArray());

action on jbutton press

I can't figure out how to make the following code work. When you press a jbutton I want it to run the following code. My problem is that the ArrayList list is located in the main and I don't know how to pass it into this method provided to me by the GUI builder so that, that actionperformed method will know what list is and return an ArrayList back to the main to replace it with the new changes.
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Student temp;
Picker pick = new Picker(list);
temp = pick.randomNoReplace(); //replace randomNoReplace() with radio button choice
list.remove(temp); //the next line must be temp.increaseScore() or temp.decreaseScore() or neither
list.add(temp);
}
}
What you are looking for is something like this:
class Foo {
private ArrayList<Student> list;
...
This will declare list as an ArrayList of Students as an instance variable so that each object of this class can access list from any instance method. Just be sure to instantiate list before using it, preferably inside your constructor doing something like this:
list = new ArrayList<Student>();

ActionListener does not work to move data from on JList to the Other JList by the button

My program is based on a API. I got a JList with and a model that has a some names. And a selectListener to get the seleted item and a button to send that item to the other window which has another Here is my first list:
First List (window) and send the items to the other list.
final DefaultListModel<String> Names = new DefaultListModel<String>();
final JList<MyAPI> Places = new JList(Names);
private JList<MyAPI> locList;
private DefaultListModel<MyAPI> favourites;
public AddLocation(JList<MyAPI> locList, DefaultListModel<MyAPI> favourites){
this.locList = locList;
this.favourites = favourites;
}
addThis.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
Object chose = Places.getSelectedValue();
favourites.addElement((MyAPI) chose); // error in this line
}
});
And this is the other window that selected items should be added to here:
final DefaultListModel<MyAPI> favourites;
final JList<MyAPI> locList;
favourites = new DefaultListModel<MyAPI>();
locList = new JList<MyAPI>(favourites);
So now both windows loads and the first list loads with its names in it. but when I press the button add this, it gives error and points to this line:
favourites.addElement((MyAPI) chose);
How can I solve it?
Your first model is defined like this:
final DefaultListModel<String> Names ...;
Your second model is defined like this:
final DefaultListModel<MyAPI> favourites;
Your first list model conains String instances, your second model contains MyAPI instances. So when this line is executed:
favourites.addElement((MyAPI) chose);
you are trying to make a MyAPI out of a String, which does not work and probably a ClassCastException is thrown.
Either you need to declare the second list model as final DefaultListModel<String> favourites; or you create an instance of MyAPI based on the selected String (new MyAPI(chose) ?).

Removing an item from the JList using ListModel as model type

I have the JList which is using ListModel and not the DefaultListModel. I don't want to change the type now because I am using this in many places. I want to remove a selected item from the same list. How do i do this? I am using the following code but its not working for me.
made_list.removeSelectionInterval(
made_list.getSelectedIndex(), made_list.getSelectedIndex());
--EDIT--
I am using the following code when I create my list:
made_list = new javax.swing.JList();
made_list.setModel(new DefaultListModel());
And then in the JButton mouseclick event, I am using the following code to remove the selected item from the list when the button is pressed
private void removeActionPerformed(java.awt.event.ActionEvent evt) {
//made_list.removeSelectionInterval(made_list.getSelectedIndex(),
//made_list.getSelectedIndex());
System.out.println(made_list.getModel());
DefaultListModel model = (DefaultListModel)made_list.getModel();
model.remove(1);
}
removeSelectionInterval removes nothing from the model or the list except the selection interval. The list items remain unscathed. I'm afraid that you're either going to have to extend your ListModel and give it a removeItem(...) method as well as listeners and the ability to fire notifiers, etc... a la AbstractListModel -- quite a lot of work! If it were my money, though, I'd go the easy route and simply use a DefaultListModel for my model as it is a lot safer to do it this way, a lot easier, and will take a lot less time. I know you state that you don't want to use these, but I think you'll find it a lot easier than your potential alternatives.
An example of an SSCCE is something like this:
import java.awt.event.*;
import javax.swing.*;
public class Foo1 {
private String[] elements = {"Monday", "Tueday", "Wednesday"};
private javax.swing.JList made_list = new javax.swing.JList();
public Foo1() {
made_list.setModel(new DefaultListModel());
for (String element : elements) {
((DefaultListModel) made_list.getModel()).addElement(element);
}
JButton removeItemBtn = new JButton("Remove Item");
removeItemBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
removeActionPerformed(e);
}
});
JPanel panel = new JPanel();
panel.add(new JScrollPane(made_list));
panel.add(removeItemBtn);
JOptionPane.showMessageDialog(null, panel);
}
private void removeActionPerformed(ActionEvent e) {
System.out.println("made_list's model: " + made_list.getModel());
System.out.println("Model from a fresh JList: " + new JList().getModel());
DefaultListModel model = (DefaultListModel) made_list.getModel();
if (model.size() > 0) {
model.remove(0);
}
}
public static void main(String[] args) {
new Foo1();
}
}
You've been given a link to different sections of the Swing tutorial in the past to help solve problems. This was done for a reason. It helps solve your current problem. It gives you a reference for future problems.
All you need to do is look at the Table of Contents for the Swing tutorial and you will find a section on "How to Use Lists" which has a working example that adds/removes items from a list. Please read the tutorial first.
Or if you can't remember how to find the Swing tutorial then read the JList API where you will find a link to the same tutorial.
//First added item into the list
DefaultListModel dlm1=new DefaultListModel();
listLeft.setModel(dlm1);
dlm1.addElement("A");
dlm1.addElement("B");
dlm1.addElement("C");
// Removeing element from list
Object[] temp=listRight.getSelectedValues();
if(temp.length>0)
{
for(int i=0;i<temp.length;i++)
{
dlm1.removeElement(temp[i]);
}
}

Categories