Adding attributes to jButton [JAVA] - 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.

Related

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.

Java ActionCommand

Is there a method to get the button associated with a particular command string?
For instance if I define a button with:
button.setActionCommand("unique_toggle");
Having that string "unique_toggle", is it possible to retrieve that button from another class? I am beginner at Java, excuse if this question may seem obvious to you.
Yes, you can access to your button and its associated button's command. If you need to a button's command, that possibly means that you should consider redesining your programm because this approach is not advisable and very dirty way to do what you want to achieve.
When it comes to answer to your question,
Lets say Foo1 is your GUI class.
class Foo1{
JButton button;
public Foo1(Foo2 otherClass)
{
button = new JButton();
otherClass.setButtonAddress(button);
}
..... other methods
}
Foo2 is the class, in where you want to access button's command text.
class Foo2{
JButton buttonFromOtherClass;
//This is the method, in where you need command string of the button
private void getCommandsString()
{
Foo1 foo1 = new Foo1(this);
//After the initialization of Foo1, you can get every information of the button
String actionCommand = buttonFromOtherClass.getActionCommand();
}
public void setButtonAddress(JButton button)
{
buttonFromOtherClass = button;
}
}

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

Java NetBeans GUI Key Event sending

I'm making a simple calculator, so far I did a text field where I can type numbers and it listens if key was typed from keyboard.
private void resultKeyTyped(java.awt.event.KeyEvent evt) { }
What I want is to click on let's say '1' with mouse and send a key event to this method, so it would be like I clicked it on keyboard. Tried doing keypress with robot but it says 'void type is no good here' or something like that. I wanted to just run that resultKeyTyped method from withing mouse click listener, like this:
private void jButton1MouseClicked(java.awt.event.MouseEvent evt)
{
resultKeyTyped(KeyEvent.VK_1);
}
To call the resultKeyTyped, you have to pass a KeyEvent. You can just create a KeyEvent using appropriate constructor:
KeyEvent event = new KeyEvent(textField, 0, System.currentTimeMillis(), 0, KeyEvent.VK_1);
resultKeyTypes(event);
Although from your description (eg simple calculator), it sounds like you may wish to choose a different approach:
Add an ActionListener to the JButton
Within the implementation of the ActionListener, change the JTextField text by using the setText method
The best way to do this (assuming that you are clicking on a Button instead of something else) in my opinion would be this:
Button button1 = new Button("1");
button1.addActionListener(new ActionListener() {
int thisKey = KeyEvent.VK_1;
#Override
public void actionPerformed(ActionEvent e) {
resultKeyTyped(thisKey);
}
});
Now, the one thing that you need to change is that resultKeyTyped needs to take an int as a parameter instead of a keyevent. From what I understand, all that you care about is which key was pressed, not how long it was pressed or anything like that. So, wherever you call resultKeyTyped, pass it KeyEvent.getKey()
Hopefully this helped!
P.S. if you really want a keyevent, you can use the keyevent constructor, but since you were using a robot anyways, I am pretty sure that you only care about the key

Pass Unique JButton Data to Another Class on Click

I am making a program where clicking a custom JButton allows you to make your next click paint an image at the point on the screen. Members of this JButton class have certain data that is unique to each separate button. My question is if I can pass the JButton object when clicked on through a method into a class which would then extract the data. I was thinking something like this:
Click Method in JButton{
OutsideClass.setObject(this); //problem
}
OutsideClass{
Object obj = new Object();
public void setObject(Object Obj){
obj = Obj;
}
Click Method in OutsideClass{
place obj;
obj.getData;//Methods within JButton that retrieve specific data
}
My issue is the "setObject" part of the JButton. It doesn't recognize "this" as the specific Object clicked and thus doesn't work. Is there another way to get the desired effect? Thanks!

Categories