How to remove an item from a jlist - java

I have a Jlist which is populated with books, however, what I would like to do is that once one of the books is selected I press a button called return book that should make the book removed from the list.
I have a members class that has a return book method as follows
public void returnBook(Book aBook)
{
currentLoans.remove(aBook);
aBook.setBorrower(null);
}
On my main application I have the following code under the return book button
private void theButtonActionPerformed(java.awt.event.ActionEvent evt) {
//!!!Return book
DefaultListModel model = (DefaultListModel) BooksOnLoan.getModel();
Book selectedBook;
selectedBook = (Book)BooksOnLoan.getModel();
model.remove(selectedBook);
}
As you can see I am quite not sure how to remove the item from the list once the button is clicked.

The method "remove" from DefaultListModel works with index, so you first need to get the index of the element that you want to remove and provide that to the remove method. You can use methods on your list for that: getSelectedIndex method for single selection mode (you will get -1 if there is no selection), or getSelectedIndices for multiselect.
If in any case your list stays the same after this, you need to refresh GUI after the model has been changed. Although I am almost certain that you need not do that, but keep this principle in mind for future.

Related

Multiple JComboBoxes with same data, every item choosable once

I'm growing desperate here ...:
I do have a FRAME with 40 JComboBoxes. At first, they offer all the same items.
If I choose on item in one specific ComboBox, it should be selected there and not be available in all the other 39 Boxes anymore.
I tried to use a ComboBoxModel for a long while, but now I think it doesnt make any sense: the Moment i remove the selected item from the model, it gets removed from the Box that it got selected in, too.
So does it make sense to do it like this:
Have 40 MyComboBoxes in the class GUI
Every MyComboBox implements an ItemListener
If an item is selected, the item gets removed from the other 39 lists;
if its deselected, it gets added to the other 39 lists
(but if I want to do it like that, the listener mustnt be an own class but the
itemEventChanged-method must be implemented anonymously in the GUI?!)
There's a better way, isnt it? Thanks a lot for your help!
for(int x =0;x<YourComboBoxArray.length();x++
{
if(e.getSource()==YourComboBoxArray[x])
{
try
{
ArrayList <String> OptionsList = new ArrayList();
for(int i=0;i<YourComboBoxArray[x].getItemCount();i++)
{
OptionsList.add(TeamPlayercmbx[x].getItemAt(i).toString();
}
DefaultComboBoxModel DCMB = new DefaultComboBoxModel(OptionsList.toArray());
YourComboBoxArray[x+1].setModel(DCMB);
YourComboBoxArray[x+1].removeItem(YourComboBoxArray[x].getSelectedItem());
}
catch(Exception ex)
{
//Log your errors or whatever you want to do if it's the last ComboBox in the Array
}
}
}
This assumes you have an action listener on each index of the Combo Box Array

Retrieve OBJECT from a navigation View (drawer) dynamically android/java

Once again stuck dead in my coding tracks, I come seeking knowledge from the omniscient StackOverflow Community...
My problem is fairly simple. I have populated a Navigation View drawer with objects. These objects toString() methods have been overwritten to display each objects own name in the list. Clicking each object in the drawer list brings up an alert message that should say ("you clicked "+ myDrawerObject.getName()) The problem is in the onNavigationItemSelected listener.
This method returns a MenuItem item which is a view. I am having trouble understanding why i can not treat this view like the object it is supposed to contain. Help is greatly appreciated and thanks in advance!
I understand that the item parameter is returning which menu item has been clicked but if the menu item is an object why cant I call those objects methods?
I have tried grabbing the item return value and calling its getName() method, to no avail. item.getName(); (I understand that item is a view so it doesnt have a "getName()" method
I have tried casting the item value back into an object to no avail
MyObject myObject = (MyObject)item;
//Item is still a view and a view cant be cast into an object it seems
I have even tried putting all created objects of the MyObject type into a static arrayList then trying to match up id's also to no avail.
//in the onNavigationItemSelected listener
int id = item.getItemId()
//somewhere else in the code
for (anotherMyObject : listOfEveryMyObjectEverMade){
anotherMyObject.get(id)
}
/*returns the id of the item in the listview. as i understand a specific id
is assigned to every item in the list. so if an object has never been in that
particular list, it wont have that same id
*/
I must add the the contents of the drawer (the string list) was created dynamically so there is no xml file for the menu or menItems!
I ran into a very similar situation and literally blockaded me for days!
I'm almost 90% positive that there has to be a way out there...
but I personally didn't find it, so instead I went with a work around:
private void setMenus() {
int temp = 0;
//Mine was inside of a fragment, hints the getActivity() call
NavigationView navView22 = getActivity().findViewById(R.id.navigation_view);
MenuItem oneItem = navView22.getMenu().findItem(0);
if (oneItem == null){
Menu m = navView22.getMenu();
SubMenu sm0 = m.addSubMenu(
getResources().getString(R.string.clickToSelectRookies));
sm0.add(0,
temp, temp, getResources().getString(R.string.signAllString));
tempRooks.add(round1.get(0));
/*I had to create the entire menu dynamically, so I did so by creating
subMenus in my menus in numerical order
I then created an arraylist to hold all my objects in that same order
though in retrospect I should have just used a HashMap!!
finally in the onClick I was able to listen for which subMenu item was clicked
and since the menu's and my arraylist of objects corresponded I then pulled
the correct object from my arraylist. I realize this is a little hacky, but
hopefully if you do not find the answer you can do this temporarily.
If you do find a better solution please post so we all can learn. Thank YOU!!
*/
temp++;
SubMenu sm1 = m.addSubMenu(
getResources().getString(R.string.firstRoundPicks));
for (int x = 0; x < round1.size(); x++) {
sm1.add(0, temp, temp, round1.get(x).toString());
tempRooks.add(round1.get(x));
temp++;
}

JavaFX - Cannot Refresh/Update ListView

Well it appears I have been stumped by one of the simplest ListView implementations out there. For a few days I have found it impossible to properly reallocate a JavaFX ListView. I am working on making an EntityView completely dynamic, being able to remove elements whenever needed through a ContextMenu. So I have a ListView that is populated by an ArrayList, which we will refer to as "renderable". When you select "Remove" in the context menu, it removes the Entity from the renderable list, which also happens to be the "value" of the List Cell on whom I right clicked. Afterwards, I wish to refresh the ListView and remove now the nonexistent cell. So by creating a new ObservableList with the new renderable list (which removes the correct entity and that works fine), I set the items in the ListView, which does jack shit. I can set the list to null in this case, which removes all the elements. But I cannot reset the list with the new array and it remove the now missing entity. Somebody point me in the right direction please!
When I use the method I stated above, it removes it from the list, but not visually. There becomes an unusable cell at the bottom of the list, which has its name.
public void createContextMenu(final Entity curr, MouseEvent me){
MenuItem[] items = {new MenuItem("EDIT TYPE"), new MenuItem("REMOVE")};
ContextMenu menu = new ContextMenu(items);
menu.show(list, me.getScreenX(), me.getScreenY());
items[1].setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent arg0) {
CanvasTab tab = (CanvasTab) core.canvasTabbedPane.getSelectionModel().getSelectedItem();
Kanvas k = tab.canvas;
k.renderable.remove(curr);
System.out.println(k.renderable);
k.redraw();
EntityView.this.list.getItems().remove(curr);
ObservableList<Entity> temp = FXCollections.observableList(k.renderable);
EntityView.this.list.setItems(temp);
}
});
}
This is the context menu:

JList - selecting option

how do i go do this, based on input in textfield, you get some results inside jlist, after you select option in jlist you then get an action, code examples would be appreciated... this is what i got so far:
final DefaultListModel<String> locations = new DefaultListModel<String>();
getTextFieldSearch().addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for(int i=0;i<10;++i) {
locations.add(i, "blah");
}
}
});
JList<String> list_racentRaces = new JList<String>(locations);
Start by taking a look at How to Use Lists, which has lots of awesome code examples.
The basic idea would be to...
When your actionPerformed method is triggered, create a new DefaultListModel, assuming you don't have your own implementation, fill it with all the new items you need and apply it to the instance of list_racentRaces
If you want to maintain what was previously in the list, you should consider starting with a DefaultListModel and simply add the new items to it as you need to...
Then, attach a ListSelectionListener to list_racentRaces and when the valueChanged event is triggered, find the selected item(s) and do what ever you need to based on these result(s)
You can find more details and examples through How to Write a List Selection Listener

How can I (un)hide a SWT TableItem?

I am trying to allow my user to search through a table of information, dynamically hiding/showing results that contain the search. I have the hiding part down, and it works well, but I'm having trouble showing the table item again once the search criteria is changed.
Here is my hide code:
searchField.addModifyListener(new ModifyListener() {
#Override
public void modifyText(ModifyEvent arg0) {
modified = true;
for (int i = 0; i < table.getItems().length; i++) {
if (!(table.getItem(i).getText(2)
.contains(searchField.getText()))) {
table.getItem(i).dispose();
}
}
if ("".equals(searchField.getText())) {
modified = false;
//where I would want to un-hide items
}
}
});
Looking at your code, it seems you try to hide the item by calling dispose(). If you dispose a widget, it is gone for good. You cannot get it back.
If you want to unhide it again, will have to create a new item at the position of the previously hidden one with the same content.
Isn't it better to actually operate with some kind of a table model and JFace bindings, rather, then do it like that? And yes, disposing is not hiding. You should probably remove the item from the table.
You have probably to save the data from TableItem into collection before you call dispose. Then when you search again you could check that collection and if matches are found, then insert back into Table by creating new TableItem.

Categories

Resources