Why is the ActionPerformed performed several times? - java

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.

Related

How to implement an action listener with generic enums?

I am in the process of refactoring my application and my teacher recommended that I replace the GUI builder generated code with a more generic one.
Right now every JMenuItem has its own action listener. What I'm trying to achieve is a sort of generic control function for every menu item by using enums in a single action listener. The code below should give you a general idea. clE is the enum key and I believe the enum should implement an interface for reading its label.
I've been doing a bit of research and I'm sure it's something simple, but I can't get fully grasp it yet. Thanks in advance!
public class JECheckBox<E extends ENUM_Label_INTF<?>> extends JCheckBox {
private final E clE;
// +++++++ CONSTRUCTOR +++++++++
public JECheckBox(final E clE) {
super( ((GetLabelINTF) clE).GetLabel() );
this.clE = clE;
}
public E GetKey() {
return clE;
}
}
I believe the enum should implement an interface for reading its label.
If you want to read the text of the check box, then you create a generic listener by doing something like:
Action action = new AbstractAction()
{
#Override
public void actionPerformed(ActionEvent e)
{
JCheckBox checkbox = (JCheckBox)e.getSource();
System.out.println( checkbox.getText() );
}
};
Now you can add the Action to each check box.
Note an Action is a more versatile ActionListener. Read the section from the Swing tutorial on How to Use Actions for more information and examples.
Not suew what you mean by generic enums. Try giving every menu item (or any component) it's own name using component.setName(SomeEnum.soneValue.toString()). Then get the name in the action listener and do a switch(SomeEnum.valueOf(name).

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

How do I read the information of a JTextField from a separate class using an ActionListener

The following code is within a class that has the buttons and checkboxes defined. The problem that I am having is with the lines "String text = txtField.getText();" and "chkAccount.withdraw(amount);".
I have a separate class file that defines the txtField and am trying to get the text that has been input into that box. The error I see is "cannot find symbol". I have looked into it but cant find information in depth enough to answer my question.
The second line refers to the object chkAccount which is derived from a separate class "Account" and instantiated in the main class of my program. The error for this is the same as the above.
//Button Listeners Class
withdrawalBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//Execute this code when the button is pressed
if(checking.isSelected()) {
String text = txtField.getText();
int amount = Integer.parseInt(text);
try {
chkAccount.withdraw(amount);
} catch (InsufficientFunds ex) {
int messageType = JOptionPane.PLAIN_MESSAGE;
JOptionPane.showMessageDialog(null, "Balance too low" +
"or amount entered not an Interval of 20.",
"Notice", messageType);
}
}
I can't really tell what the code that you've provided is trying to do, but just based on the title of your question, I would recommend you have the class that you want the information to go to extends ActionListener, add an object of that type of class (the one that you had extend ActionListener) as an ActionListener to the JTextField, and then in the actionPerformed method (which you'll have to add, as the class now extends ActionListener) use ActionEvent.getSource (and cast) to get the JTextField! From there, you can extract the information that you need.

Adding attributes to jButton [JAVA]

Lets say i have an array of 100 employees. Each employee in the array, is an instance of the class Employee, that have many attributes, such as name, direction, salary, etc.
I want to display, 1 button for each employee in the array, and when you click one, you get the information of that employee.
What i don't know, is how can i link a button to an specific employee. I Was thinking on, somehow, attaching an Integer variable to the button, so i know which employee is related to that specific button, but, i don't really know how to do that.
Anyone cares to give me some advice on this?
You could use setName(employeeId) method for JButton to set Employee's id or use putClientProperty("id", employeeId), when you get a callback at button's listener you could get the name or your property.
You can use the putClientProperty and getClientProperty to attach any object to a JComponent.
If you get "this" inside listener you get a reference to listener's object. You should use getSource() method, like:
JButton j = new JButton("click here");
j.putClientProperty("id", "employee1");
j.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ae) {
JButton source = (JButton)ae.getSource();
String id = (String) source.getClientProperty("id");
System.out.print(id);
}
});
Will print - employee1.

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.

Categories