How to Add Element to JList in swing? - java

Hi i am newbie to java and i am trying to add the item from JComboBox to the JList, but when i run the program, i am getting this error.
How to do this?
error:
cannot find symbol
symbol : method addElement(java.lang.String)
location: class javax.swing.JList
openTaskBox.addElement(taskItem);
code:
public static void addSelectedItemToTaskList(String taskItem)
{
openTaskBox.addElement(taskItem);
}
Here openTaskBox is JList.
Code:
JList openTaskBox = new JList();
openTaskBox.setPreferredSize(new Dimension(350, 50));
pnlInnerTL.add(openTaskBox);

For JComboBox
You can use JComboBox#addItem(E)
See How to use Combo Boxes for more details
For JList
You have to use the ListModel. DefaultListModel supplies a addElement method
See How to use lists for more details

Add the item to the JList's model, not to the JList itself.
DefaultListModel model = (DefaultListModel) openTaskBox.getModel();
model.addElement(taskItem);

Related

How to dynamically add items to a JList?

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

JList created in Netbeans won't allow me to addElement

This is the automatically created code when adding the Jlist in Netbeans design mode:
jListResult = new javax.swing.JList();
jListResult.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
jScrollPane1.setViewportView(jListResult);
I don't understand why an object of type Jlist would not be able to use the method .addElement How can I fix this?
addElement is provided by the DefaultListModel not the JList itself
DefaultListModel<String> model = new DefaultListModel<>();
JList jListResult = new JList(model);
model.addElement(...);

How to handle multiple jLists with one ListSelectionEvent

I have three jLists in my class frmMain. I have created a class called ListActions. The code below is working for one jList. It returns the value clicked for one jList.
How do I distinguish between the three other jList? Or do I need to create a seperate class for each listener?
I need to perform an action based on which jList was clicked. I attempted to see if I could access the variable name of the jList that was clicked, but couldn't find a way to do this...
class ListActions implements ListSelectionListener {
public void valueChanged(ListSelectionEvent evt) {
if (!evt.getValueIsAdjusting()) {
JList list = (JList) evt.getSource();
int iSelectedDatabase = list.getSelectedIndex();
Object objSelectedDatabase = list.getModel().getElementAt(iSelectedDatabase);
String sSelectedDatabase = objSelectedDatabase.toString();
JOptionPane.showConfirmDialog(null, sSelectedDatabase);
}
}
}
Thanks,
- Jason
JList inherits from Component.
Therefore, you can use the getName() method to get the name of your Component and know which one has been called.

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

How to load already instantiated JComboBox with data in Java?

I have a Swings GUI which contains a JComboBox and I want to load data into it from the database.
I have retrieved the data from the database in a String Array. Now how can I populate this String array into the JComboBox
EDITED====================================================================
In actual, the JComboBox is already instantiated when the java GUI is shown to the user. So I can't pass the Array as a paramter to the constructor.
How can I populate the already instantiated JComboBox?
The following is the code that is Nebeans generated code.
jComboBox15 = new javax.swing.JComboBox();
jComboBox15.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "12" }));
jComboBox15.setName("jComboBox15");
Can I set another ComboBoxModel to the above jComboBox?
Ah, the combo box is already instantiated.... In that case just clear the contents and add the new array item by item:
comboBox.removeAllItems();
for(String str : strArray) {
comboBox.addItem(str);
}
Make sure this is done from the EDT!
Here's an excellent article about it: How to use Combo Boxes ( The Java Tutorial )
Basically:
String[] dbData = dateFromDb();
JComboBox dbCombo = new JComboBox(dbData);
You'll need to know other things like
Using an Uneditable Combo Box
Handling Events on a Combo Box
Using an Editable Combo Box
Providing a Custom Renderer
The Combo Box API
Examples that Use Combo Boxes
That article contains information about it.
EDIT
Yeap, you can either do what you show in your edited post, or keep a reference to the combo model:
DefaultComboBoxModel dcm = new DefaultComboBoxModel();
combo.setModel( dcm );
....
for( String newRow : dataFetched ) {
dcm.addElement( newRow )
}
new JComboBox(stringArray);
A useful tip - when you know what class you are working with, check its javadoc. It most often contains the information you need.
Edit: after your update, use:
for (String string : stringArray) {
comboBox.addItem(string);
}
(my tip still applies)
I think that what NetBeans does is what you need.
From wherever you want, you can create a DefaultComboBoxModel object and then invoke comboBox.setModel(defaultComboBox);
Here is a very small example of what I think you want to do: when the user clicks the button "Change data" the comboBox is filled with data from an array (method actionPerformed).
public class TestJComboBox extends JFrame {
private JComboBox comboBox = new JComboBox();
public TestJComboBox() {
JButton changeComboBoxData = new JButton("Change data");
changeComboBoxData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
DefaultComboBoxModel cbm = new DefaultComboBoxModel(
new String[] { "hola", "adios" });
comboBox.setModel(cbm);
}
});
super.setLayout(new BorderLayout(10, 10));
super.setSize(100, 100);
super.add(changeComboBoxData, BorderLayout.NORTH);
super.add(comboBox, BorderLayout.SOUTH);
}
public static void main(String[] args) {
new TestJComboBox().setVisible(true);
}
}
JComboBox jComboOperator = new JComboBox();
arrOperatorName = new String []{"Visa", "MasterCard", "American Express"};
jComboOperator.setModel(new DefaultComboBoxModel(arrOperatorName));

Categories