How to handle multiple jLists with one ListSelectionEvent - java

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.

Related

How can I simplify this module?

I have some method which looks awful(especially number of parameters). I wonder how can I make this code cleaner.
The method works with JLists and setting a new model(DefaultListModel). So it just swaps items between two JLists and deletes swapped item in list where was the item taken.
Сriticism and advice are welcome.
Call the method example:
moveToOtherJList(newOrdersModel, newOrdersJList, inProcessOrdersModel, inProcessOrdersJList);
The method:
private void moveToOtherJList(DefaultListModel firstModel, JList firstJList, DefaultListModel secondModel, JList secondJList)
{
int selectedIndex = firstJList.getSelectedIndex();
secondModel.addElement(firstJList.getSelectedValue());
secondJList.setModel(secondModel);
firstModel.remove(selectedIndex);
}
I have some method which looks awful(especially number of parameters).
Well there is no need to pass either ListModel, since you can get the ListModel from the JList.
So I would define the method as:
public void moveToOtherJList(JList fromJList, JList toJList)
{
int selectedIndex = fromJList.getSelectedIndex();
DefaultListModel fromModel = (DefaultListModel)fromJList.getModel();
DefaultListModel toModel = (DefaultListModel)toJList.getModel();
toModel.addElement(fromJList.getSelectedValue());
fromModel.remove(selectedIndex);
}

Why is the ActionPerformed performed several times?

I have a small issue and I'm sure it's a stupid mistake but here I go.
I have a GUI containing amongst other objects a JComboBox and a JButton.
The ComboBox (called orderTypeChoices in my code) contains the names of objects in an "enum" called OrderType.
This is my enum :
public enum OrderType {
BUILD_SCREENING_CENTER,
INCREASE_TAXES,
RESEARCH_MEDICINE,
RESEARCH_VACCINE
}
In my code, there is a method called executeOrder that executes other code, depending on the OrderType. I'm pretty much sure the error isn't here.
The context is that I need to check in the JComboBox which item is selected, so when I click on the button, the executeOrder will use what's selected as Item.
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String orderName = (String) cloudPandemic.orderTypeChoices.getSelectedItem();
for (OrderType orderType : OrderType.values()) {
if (orderType.name().equals(orderName)) {
System.out.println(orderType.name());
cloudPandemic.executeButton.addActionListener(e1 -> cloudPandemic.simulation.executeOrder(OrderType.valueOf(orderName)));
break;
}
}
}
};
this.cloudPandemic.orderTypeChoices.addActionListener(actionListener);
So I added 2 ActionListeners (one to the ComboBox and the other to the Button). I store in a String the String name of the Item and check in my enum if one of the objects in it matches namewise. If it does, I add an ActionListener to the button, in which I use the method executeOrder. However, I've noticed that it tends to accumulate : If I choose at first one Item, it'll work, if I choose another Item, it'll execute on both this item and the first item i've chosen, etc.
I was wondering if I missed something, because I don't see why the ActionPerformed is executing past Actions.
Thanks in advance,
Fares.

JComboBox get item

I have a quick question. I don't get it...
I've got a JFrame where I add a JComboBox:
JComboBox<String> Team_ComboBox = new JComboBox<>();
Team_ComboBox_Handler ComboBox_Listener = new Team_ComboBox_Handler();
Team_ComboBox.addActionListener(ComboBox_Listener);
Team_ComboBox.addItem("Test 1");
Team_ComboBox.addItem("Test 2");
On this Frame I have a button which opens another JFrame.
Play = new JButton();
Play.setText("Play");
Play.setPreferredSize(dimension);
Play.addActionListener(menuhandler);
private class main_menuhandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if(e.getSource()==Play){
teams Team = new teams();
Team.teams();
disposeMainMenue();
}
if(e.getSource()==Close) {
System.exit(DO_NOTHING_ON_CLOSE);
}
}
}
Anyway, I would like to transfer the Selected value of the Combobox to a method of the other class. I know how I can get the itemvalue of the combobox in the method itself (with getselecteditem) But how can I do that in the ActionPerformed Method as I can't access the combobox in the ActionPerformed method.... I created another ActionListener (comboBox_Listener) but I haven't put any code into it...
Any idea? Thanks a lot in advance
Several issues appear to me:
Your main question:
But how can I do that in the ActionPerformed Method as I can't access the combobox in the ActionPerformed method
Your likely best solution is to change your code and variable declaration placement so that you can access the JComboBox fromt he actionPerformed method. If you're declaring the combobox from within a method or constructor, change this so that it is a proper instance field of the class.
Other problems:
You should not be creating multiple JFrames. If you need a dependent window, then one should be a JDialog. If not, then consider swapping views with a CardLayout.
Learn and follow Java naming conventnions so others can better understand your code. Class names begin with capital letters and methods and variable names don't for instance.
I am not sure why you're doing this: System.exit(DO_NOTHING_ON_CLOSE);. Why pass that constant into the exit method?
Use a constructor for your action listener class:
private class main_menuhandler implements ActionListener {
private JComboBox<String> Team_ComboBox;
public main_menuhandler(JComboBox<String> Team_ComboBox){
this.Team_ComboBox = Team_ComboBox;
}
}
Now you can create the class main_menuhandlervia the constructor and add the combobox to it.
In your Overriden action you have access to it.
Try playing around with this as your code snippet isn't broad enough to actually provide proper code. But this should answer your question

Updating JList by pressing button

first of all I will introduce what I am trying to do. This is an assignment in university we are making Hotel booking system with JAVA. To go straight to the point, all I need to know is how to update JList when I press button.
listModel = new DefaultListModel<Hotel>();
bookingList = new JList(listModel);
class MouseAdapterMod extends MouseAdapter {
public void mousePressed(MouseEvent e) {
if(e.getSource() == searchButton){
for(lists.getRoomsList() p : lists.getRoomsList())
{
listModel.addElement(p);
}
bookingList.setModel(listModel);
}
In this GUI class I have instance variable (lists) of Hotel class, in Hotel class there are methods
public ArrayList<Rooms> getRoomsList()
{
return roomsList.getListRooms();
}
public ArrayList<Suite> getSuitesList()
{
return roomsList.getListSuites();
}
this returns whole ArrayList of Room class objects and also ArrayList of Suite class.
QUESTION would be is how to show whole ArrayList of Rooms when I press button, in other words how to update JList which consists of objects, by pressing button?
I hope I explained alright.
Your for-each loop is wrong. Try this and see:
public void mousePressed(MouseEvent e) {
if(e.getSource().equals(searchButton)){
ArrayList<Rooms> rooms = lists.getRoomsList();
for(Rooms r : rooms) {
listModel.addElement(r);
}
bookingList.setModel(listModel);
}
}
This still looks sorta messy to me though. A more appropriate approach would be to set an event handler on the searchButton, to populate the JList when searchButton is clicked.
Also, are Rooms and Suites sub classes of Hotel? If not, you'll have to create listModel like this (for rooms):
listModel = new DefaultListModel<Rooms>();

Java combo box model and get selected item

The code below shows a problem I'm having with combo actions. The getSelectedItem() is fired multiple times instead of just at selection. Simply loading the frame calls the method 3 times. Each click on the combo box is a call, even if its just for the dropdown and not the actual selection. Clicking inside the editable text area also triggers the getSelectedItem() method. Is there a way to filter this event?, or an alternate way to validate data on the box model level?
public class SSCCE {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
JFrame aframe = new JFrame();
Combo _combo = new Combo();
_combo.addElement("This");
_combo.addElement("That");
JComboBox _box = new JComboBox(new Combo());
_box.setEditable(true);
aframe.add(_box);
aframe.setVisible(true);
}
static class Combo extends DefaultComboBoxModel{
public Combo(){
}
int i = 0;
#Override
public Object getSelectedItem() {
System.out.println("Get selected Item" + i);
i++;
return super.getSelectedItem();
}
}
}
See this tutorial on how to use JComboBox, specifically the section on handling events. You should add an ActionListener to your combobox. It will be triggered when the user actually makes a gesture indicating that their selection is confirmed.
You have look at ItemListener or ActionListener added to the JComboBox
getSelectedItem() indeed fires multiple times, as well as the action event. For an editable combo box the action fires once for comboboxchanged, and once for comboboxedited. I've set up the validation that is not specific to end item in the getSelectedItem, and moved the rest into a filtered action event for comboboxchanged. I've completely ignored comboboxedited event.

Categories