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.
Related
I have been trying to populate a Eclipse GUI Java JComboBox using an Array list using constructors without any luck. This is what I have tried thus far.
import item.Item;
import javax.swing.JComboBox;
import java.util.ArrayList;
public class SelectionScreen{
private JFrame frame;
static ArrayList< Item> list;
private String items;
public static void main (String[] args){
initialize();
}
public void initialize(){
list = new ArrayList< Item >();
list.add(new Item("Strawberry,200,.25,.75);
list.add(new Item("Banana,200,.25,1.00);
list.add(new Item("Oranges,200,.25,2.00);
JcomboBox comboBox = newJcomboBox();
ComboBox.setBounds(63,29,86,22)
frame.getContentPane().add(comboBox);
// here is where I tried to fill the combobox
//comboBox.setModel(new DefaultComboBoxModel(Item.getName()))); //Wrong
//comboBox.setModel(Item.getName); //Wrong
//the following only loads the last item in the list which is Oranges
for(Item i: list{
comboBox.setModel(new DefaultComboBoxModel(New String[] {
i.getName()}));
}
// tried making a different list to collect my fruits.
for(Item i: list){
list2[ i.getName()];
Item.length;
} //which was a complete fail.
I am at complete lost here and not very experienced with Java. I can load the items just fine using
comboBox.setModel(new DefaultComboBoxModel(new String[]{ "Strawberry","Banana","Oranges"}));
but I won't know what fruits are in the list when I import them from a text file.
Any help would be appreciated.
/*The following only loads the last item in the list which is Oranges.*/
for(Item i: list)
{
comboBox.setModel(new DefaultComboBoxModel(new String[] {
i.getName()}));
}
Don't keep creating a new ComboBoxModel inside the loop. You can't add more than one item to the model if you keep creating a new model. So you only see the last model created with the single item added to it. If you want to use this approach then you would create the model OUTSIDE of the loop and then just add items the model INSIDE the loop.
Actually you don't event need to create a combo box model. You can just add items directly to the combo box:
Something like:
for(Item i: list
{
comboBox.addItem( i.getName() );
}
Another option is to add the Item object directly to the combo box. Then you can use a custom renderer to control which property of the Item object is display in the combo box. Check out Combo Box With Custom Renderer for more information on this approach.
If you wish to show Item objects in a combobox then you should declare the JComboBox to store Item objects. That way you can easily add items without having to do any mucking around with models at all:
JComboBox<Item> itemsCombo = new JComboBox<>();
list.forEach(itemsCombo::add);
The value displayed in the combobox will be whatever is returned by Item.toString. If that's not what you want (because your toString returns a more complete description of the object - generally considered better practice) then it is fairly easy to write your own Custom Renderer.
The only hackish downside of the JComboBox API is that you've got to cast the selected item:
Item selectedItem = (Item)itemsCombo.getSelectedItem();
This is ugly and I wish the API didn't require it but it's a small price to pay to avoid having to define your own model.
You can, in fact, avoid the cast by:
Item selectedItem = itemsCombo.getItemAt(itemsCombo.getSelectedIndex());
But that's just about as ugly.
As an aside, this is one of several areas in which the standard Java tutorial and samples are quite out of date so there's no blame here at all for not knowing to use generics.
I have a simple library application, and one thing it needs to accomplish is checkout/return books. In that checkout/return window, I have two tables, a "Book List" table, which starts full of books I already have stored, and a "Checkout/Return" table, which starts out empty. The Checkout/Return table is populated by double clicking items in the Book List table, and then depopulated by double clicking items displayed within itself. Double clicking adds or removes the book items to/from a checkout/return ArrayList (which is then displayed in the table).
What I'm looking for is a way to filter out books in the Book List table by the contents of the Checkout/Return ArrayList. (Unable to post images of desired effect at this time).
Is this even possible, and if so, how similar is this to filtering by the contents of a JTextField?
Edit: I've since found this approach: http://pulkitsinghal.blogspot.com/2010/06/multiple-row-filters-for-jtable.html.
RowFilter<TableModel, Object> firstFiler = null;
RowFilter<TableModel, Object> secondFilter = null;
List<RowFilter<TableModel,Object>> filters = new ArrayList<RowFilter<TableModel,Object>>();
RowFilter<TableModel, Object> compoundRowFilter = null;
try {
firstFiler = RowFilter.regexFilter(yourRegexString, columnIndex);
secondFilter = RowFilter.regexFilter(yourRegexString, columnIndex);
filters.add(firstFiler);
filters.add(secondFilter);
compoundRowFilter = RowFilter.andFilter(filters); // you may also choose the OR filter
} catch (java.util.regex.PatternSyntaxException e) {
return;
}
sorter.setRowFilter(compoundRowFilter);
However, this achieves the opposite affect I want. Rather than filtering out everything that doesn't match the filter input, I want to filter out everything that does match the filter input.
I have a JList with some elements where multiple selection is allowed. Before these elements are added to the JList, some information about them is being stored in a static HashMap in a separate class. When more than 1 items are selected and the 'Remove selected' button is pressed, I am trying to remove the selected items (which works fine) and also delete their records from the HashMap. For some reason though, if I select more than 1 elements, only the first record in the HashMap is removed. I don't understand how this works for the JList but doesn't work for the HashMap. My code below:
remove.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
Object[] selectedElementsValues = jList.getSelectedValues();
for (int i = 0; i < selectedElementsValues.length; i++) {
System.out.println(jList.getSelectedValue().toString());
System.out.println(PersonClass.map.get(jList.getSelectedValue().toString()));
PersonClass.map.remove(jList.getSelectedValue().toString());
System.out.println(PersonClass.map);
}
It works fine if I select only one item at a time and remove it. But not with multiple selection. The items from the JList are removed properly, though, so I don't see why it doesn't do the same for the map.
Thx
The problem is that the loop that removes items from the map uses jList.getSelectedValue().toString(), when the jList selection is not modified. You can use the selection array you obtained earlier:
for (Object o : selectedValues) {
PersonClass.map.remove(o.toString());
}
Note that getSelectedValues() is deprecated, and you should use getSelectedValuesList() instead.
Is there another way to remove all items of a JComboBox then removeAllItems()? I use 2 JComboBoxes in mij app and when you select an item from the first combobox the related items should then be shown in the second combobox. When I do this, the items just keep appending after the ones that were already there. When I then first try to clear the combobox by using removeAllItems(), the second combobox is empty and stays empty whenever I change the first combobox... The first combobox keeps all its values... Does anyone see my problem?
festival is the JComboBox:
private JComboBox festival;
private JComboBox zone;
...
public void fillFestivalList(){
festival.removeAllItems();
List festivals = OP.fillFestivalList();
for(Object fest: festivals)
festival.addItem(fest.toString());
}
public void fillZoneList(String festival){
zone.removeAllItems();
List zones = OP.fillZoneList(festival);
for(Object zoneItem: zones)
zone.addItem(zoneItem.toString());
}
Regarding,
Is there another way to remove all items of a JComboBox then removeAllItems()?
Simply give the JComboBox a new model.
I would create a new DefaultComboBoxModel<T>, fill it with the newest entries, and then call setModel(...) on my JComboBox, passing in the new model when desired.
You can also Remove all the items in this way ,
but better to Give JCombobox a new DefaultComboBoxModel like the way #Hovercraft Full Of Eels said
int itemCount = combo.getItemCount();
for(int i=0;i<itemCount;i++){
combo.removeItemAt(0);
}
I have a JList with a few items, Then I got an API that need to get the selected item and use it to provide some information about that item. My problem is that the type of the JList is String and the type of my API is obviously something different. Lets say LocationAPI. So the API gets index only from its own type and not other ones. I am looking for a solution to convert the selected item (String) to something suitable for the API. Here is a simple example of the API.
LinkedList<LocationAPI> stations = FetchWeatherForecast.findWeatherStationsNearTo("cityName");
for (LocationAPI station : stations) { System.out.println(station); }
// Assume the first match on the list is correct
LocationAPI firstMatch = stations.getFirst();
List<ForecastForOneDay> forecast = FetchWeatherForecast.getWeatherForecast(firstMatch);
So it is a simple example of how the API works, But Instead of 'firstMatch' and 'Station' I have to use my own items and lists. I got the Item and list, but I made them differently:
DefaultListModel<String> cityPlace = new DefaultListModel<String>();
JList myList = new JList(cityPlace);
So how can I use the items of the above list in the API??