Java - How to update JList once Jframe has been loaded - java

Connection connection = newConnection.createConnection();
Statement newStat = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet res = newStat.executeQuery("SELECT contactName FROM Contact WHERE accountName='"+m+"'");
Vector<String> temp = new Vector<String>();
//res.first();
while (res.next()){
temp.add(res.getString("contactName"));
}
newStat.close();
connection.close();
customerContactList = new JList(temp);
repaint();
I have a Jlist with account names, when an account is selected, on the side there is a button which has to be pressed for in order to call the code above.
The code is supposed to get contact names associated to that account and populate them into
the JList. This does not happen. The Jlist stays blank, i debugged and the vector temp does get 3 values and stores them into the new jlist, the problem is, JList does not refresh.
How can I make it refresh?
Thanks a lot and I appreciate any help.
Kunal

The new JList you created hasn't been added to any container, so you'd have to add it to the frame, just as the original one was, and then call "validate()" on the frame (always necessary when you add/remove components to a visible window.) But it would be better to call setListData() on the existing JList -- it would update right away, with less flashing around.

You can use a ListModel to manipulate the data inside the JList. And definitely not create new JLists at any step.
You have your JList bounded to your JFrame. Now you can get the data inside it using
JList list = new JList();
ListModel model = list.getModel();
and modify that model, then send the new model back:
DefaultListModel listModel = new DefaultListModel();
while (res.next()) {
listModel.addElement( res.getString("contactName") );
}
list.setModel(listModel);

Related

Item Cannot added in to the jList

i am creating simple inventry system in Java.when i add the productname,price,qty click add button product information should added into the JList.how it didn't added. got the Error.
java.lang.ClassCastException: javax.swing.JList$3 cannot be cast to javax.swing.DefaultListModel
DefaultListModel model;
String panme = (txtpname.getText());
int price = Integer.parseInt(txtprice.getText());
int qty = Integer.parseInt(txtqty.getText());
int tot = qty * price;
model = (DefaultListModel)jList1.getModel();
model.addElement(new Object[]
{
panme ,
price,
qty,
tot,
});
}
If you create a JList an empty constructor or using an Array or Vector, then a read only ListModel is created.
If you want to be able to modify the ListModel then you need to specifically add a DefaultListModel to the JList:
JList list = new JList( new DefaultListModel() );
Then in your above method you will be able to access the model as a DefaultListModel.
Having said that, you should NOT be using a JList for this since you are adding multiple properties. Instead you should use a JTable which allows you to add data that you can display in rows/columns.
Read the section from the Swing tutorial on How to Use Tables for more information.

JList setSelectedValue not working

I have a JList in Swing working bad. I list all items from Database into the list with no problem with this code.
My code:
Integer index = null;
DefaultListModel<String> model = new DefaultListModel<String>();
index = DataBase.getIndex1(cbActivity.getSelectedItem().toString());
activities = DataBase.getIndex2(index);
for(MapActivity mapActitivy : activities)
{
model.addElement(mapActivity.getActivity().toString());
}
jList.setModel(model);
But now, I would like to select individual or multiple selection, but nothing I tried works. I tried:
jList.setSelectedValue("Ball", true);
//jList.setSelectedIndex(2);
jList.setSelectionBackground(Color.red);
But nothing happen. Just the list on screen with nothing selected. Single or multiple.
Any help?
Try this:
setSelectedIndex(1); // here use index of items
or if it does not work use below one:
setSelectedItem("ball") // here use name of item.

JComboBox<BeanObject> not displaying edited values

I have a Jtable, whose first column uses a JComboBox as editor. The combobox model contains data objects fetched from a sql database.
If I manually enter a value inside the combobox and then leave the editor, the entered value is lost. This doens't happen if the value is selected from the popup, or if the JComboBox's model is instantiated with simple Strings instead of bean objects.
Note that I need to add row dinamically, but this seems irrelevant since the issue appears both in the default row and in the added rows.
This is a working NetBeans sample project that reproduces my issue: https://drive.google.com/open?id=0B89FsS48-Yy4V09YRVozRzJGMkk
Here is the relevant code:
public NewJFrame() {
initComponents();
//bean objects used to populate the combobox:
Item item1 = new Item("one", 1);
Item item2 = new Item("two", 2);
Item item3 = new Item("three", 3);
JComboBox<Item> comboBox = new JComboBox<>(new Item[]{item1, item2, item3});
comboBox.setEditable(true);
DefaultCellEditor defaultCellEditor = new DefaultCellEditor(comboBox);
defaultCellEditor.setClickCountToStart(1);
jTable1.getColumnModel().getColumn(0).setCellEditor(defaultCellEditor);
}
private void addRowButtonActionPerformed(java.awt.event.ActionEvent evt) {
((DefaultTableModel) jTable1.getModel()).addRow(new Object[]{null, null});
}
Update: when the JComboBox in the table is populated via a model instead of the constructor like this,
items = new Item[]{item1, item2, item3};
JComboBox<Item> comboBox = new JComboBox<>();
comboBox.setModel(new DefaultComboBoxModel<>(items));
a manually inserted value is kept displayed, only if no selection has been made before; that is, if I first select a choice and then edit the choice, when leaving the combobox the previously selected item reappears.
None of the reported behaviours occur in a JComboBox outside the table, so this led me to think it's something related to the CellEditor.
Update 2: here's a bug report of this issue from the year 2000! They said they solved it back then but this is far from solved after 15 years.

Problem with adding JCombobox in JTable in Java?

I have added a combobox in a JTable, the adding code as follows:
Vector<String> header = new Vector<String>();
Vector data = new Vector();
String[] h = new String[]{"Music", "Movie", "Sport"};
header.add("Code");
header.add("Name");
header.add("Salary");
header.add("Hobby");
loadData(); // Add some data to the table
DefaultTableModel tblModel;
tblModel = (DefaultTableModel) this.tblEmp.getModel();
tblModel.setDataVector(data, header);
// Adding combobox to the last column
TableColumn hobbyColumn = tblEmp.getColumnModel().getColumn(3);
hobbyColumn.setCellEditor(new MyComboBoxEditor(h));
Things worked fine until I dynamically add a new row to the table using the code:
Vector v = new Vector();
v.add("E333");
v.add("Peter");
v.add(343);
v.add(""); // This last colum is the combobox so I put it as ""
data.add(v);
tblEmp.updateUI();
Data is added to the table but the combobox in the last column cannot be selected anymore. The combobox is still displayed when I click on the row but cannot select a value.
How can I handle this problem, please?
Never use the updateUI() method. Read the API to see what this method actually does. It has nothing to do with changing the data in a model.
JTable already supports a combo box editor so there is no need to create a custom MyComboBoxEditor. Read the JTable API and follow the link to the Swing tutorial on "How to Use Tables", for a working example of using a combo box as an editor.

How to transfer the elements from one JList to other JList in Java?

I have two JList on a swing GUI. Now I want that when a user clicks on a button (say TransferButton) the selected elements from one JList is added from the first JList to the second JList and remove those selected elements from the first JList.
The model doesn't know about selection.
The JList provides several methods to get the selected item or selected index. Use those methods to get the items and add them to the other list's model.
You have two JLists, then you also have their respective ListModels. Depending on how you implemented them you can just remove the elements from one model and add them to the other. Note, though, that the ListModel interface doesn't care for more than element access by default, so you probably have to implement add and remove methods there by yourself.
DefaultListModel leftModel = new DefaultListModel();
leftModel.addElement("Element 1");
leftModel.addElement("Element 2");
leftModel.addElement("Element 3");
leftModel.addElement("Element 5");
leftModel.addElement("Element 6");
leftModel.addElement("Element 7");
JList leftList = new JList(leftModel);
DefaultListModel rightModel = new DefaultListModel();
JList rightList = new JList(rightModel);
Let's imagine you have two JList components as described in the code above (left and right). You must write following code to transfer selected values from the left to the right JList.
for(Object selectedValue:leftList.getSelectedValuesList()){
rightModel.addElement(selectedValue);
leftModel.removeElement(selectedValue);
}

Categories