How to make an action command for same buttons - java

I have here just a snip of code for my button:
up = new JButton(new ImageIcon("more_buttons\\up3.png"));
up.setBackground(new Color(224,223,227));
up.setPreferredSize(new Dimension(5,15));
up.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
value1000++;
if(value1000>0)
{
number.setText(value1000+"");
down.setEnabled(true);
}
}
});
down = new JButton(new ImageIcon("more_buttons\\down3.png"));
down.setBackground(new Color(224,223,227));
down.setPreferredSize(new Dimension(5,15));
down.setEnabled(false);
down.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
value1000--;
if(value1000>0)
{
number.setText(value1000+"");
}
if(value1000==0)
{
number.setText(value1000+"");
down.setEnabled(false);
}
}
});
I'm wondering if I can make an action command for this button so that I won't have to repeat this code throughout my program. I only have to call the function like buttonaction(e) or something like that. I'm not used to creating action command but I have used it before but only for appending text. I'm not sure how to do that with a function like this. Is it possible? Or is there a more efficient way to do this?

You can add the same ActionListener to multiple buttons:
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// You can check which button was pressed and act accordingly
// simply by checking the event source:
if (e.getSource() == button1)
System.out.println("Button1 was pressed.");
else if (e.getSource() == button2)
System.out.println("Button2 was pressed.");
}
};
button1.addActionListener(al);
button2.addActionListener(al);

To remove boiler plate code, You need to at least implement an ActionListener in your class
samaple:
public class myClass implements ActionListener
It will generate an actionPerformed method After you need to add actionCommand in your button so when you click a button it will recognize it that you pressed that button
sample:
down.setActionCommand("down");
down.addActionListener(this);
up.setActionCommand("up");
up.addActionListener(this);
in the actionPerformed method
#Override
public void actionPerformed(ActionEvent evt)
{
String actionCommand = evt.getActionCommand(); //get the actionCommand and pass it to String actionCommand
switch(actionCommand) { //switch statement for each of the action command
case "down":
//down button command here
break;
case "up":
//up button command here
}
}

Take a look at How to use Actions
public abstract class AbstractNumberValueAction extends AbstractAction {
private NumberModel model;
private JTextField numberField;
private int delta;
public ValueAction(NumberModel model, JTextField numberField, int delta) {
this.model = model;
this.numberField = numberField;
this.delta = delta;
}
public void actionPerformed(ActionEvent evt) {
int value1000 = model.updateValue(delta);
if(value1000>0)
{
numberField.setText(value1000+"");
}
if(value1000==0)
{
numberField.setText(value1000+"");
setEnabled(false);
}
}
}
public class UpAction extends AbstractNumberValueAction {
public ValueAction(NumberModel model, JTextField numberField) {
this(model, numberField, 1);
putValue(SMALL_ICON, new ImageIcon("more_buttons\\up3.png"));
}
}
public class DownAction extends AbstractNumberValueAction {
public ValueAction(NumberModel model, JTextField numberField) {
this(model, numberField, -1);
putValue(SMALL_ICON, new ImageIcon("more_buttons\\down3.png"));
}
}
Which could then simply be applied as
up = new JButton(new UpAction(model, number));
down = new JButton(new DownAction(model, number));
For example...
(ps- NumberModel would be a simple class that controlled the underlying value to make is simpler to manage ;))

Related

How to properly format an ActionEvent so JButtons will work

I have set up some ActionListeners, however only 'Takeoff' works. The other buttons do not work when they are clicked. When they are clicked, nothing happens.
I have tried to create a new ButtonHandler, but that did not work.
ButtonListener l = new ButtonListener();
JButton takeoff = new JButton("Takeoff");
takeoff.addActionListener(new ButtonHandler());
takeoff.addActionListener();
grid[0][2].add(takeoff);
JButton land = new JButton("Land");
land.addActionListener(new ButtonHandler());
grid[1][2].add(land);
JButton forward = new JButton("Forward");
forward.addMouseListener(new MouseHandler(l));
forward.addActionListener();
grid[2][1].add(forward);
JButton left = new JButton("Left");
left.addMouseListener(new MouseHandler());
left.addActionListener(new ButtonHandler());
left.addActionListener();
grid[3][0].add(left);
takeoff.addActionListener(l);
land.addActionListener(l);
forward.addActionListener(l);
backward.addActionListener();
left.addActionListener(l);
right.addActionListener(l);
turnLeft.addActionListener(l);
turnRight.addActionListener(l);
up.addActionListener(l);
down.addActionListener(l);
stop.addActionListener(l);
What I want to do is move the robot drone in the correct direction, rather than just letting it sit still.
I am not sure if this part will help, but I have where my ButtonHandler implements ActionListener.
private class ButtonHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String button = e.getActionCommand();
if (button.equals("Takeoff")) {
RobotModel.takeoff();
}
else if (button.equals("Land")) {
RobotModel.land();
}
else if(button.equals("Left")) {
RobotModel.left();
}
}
}
You could use the actionCommand to invoke a method via reflection, e.g.
private void init() {
JButton left = new JButton("Go left");
// This
left.setActionCommand("left");
left.addActionListener(new MethodCallActionHandler());
// OR that
left.addActionListener(new MethodCallActionHandler("left"));
}
private void left() {
// go left...
}
private class MethodCallActionHandler implements ActionListener {
private String methodName;
private MethodCallActionHandler() {
super();
}
private MethodCallActionHandler(String methodName) {
this.methodName = methodName;
}
public void actionPerformed(ActionEvent e)
{
String button = methodName != null ? methodName : e.getActionCommand();
SurroundingClass.this.getClass().getMethod(button, new Class[] {}).invoke(SurroundingClass.this);
}
}
You could also pass the action command as String to the MethodCallActionHandler.
You can inherit the Action Listener class into your current class and then add the required methods. Then you can do takeoff.add(this)... etc.
Also nowhere are you setting the action command, that is done in the button settings.
When you are setting
String button = e.getActionCommand();
That is not what is being set when you do
JButton button = new JButton("Takeoff"); <-- This is the text associated with the button
button.setActionCommand("Takeoff");
and then it should work.

How to examine parameters in an ActionListener? [duplicate]

I've got my buttons working right, and I'm a listener to each button like this:
for(int i = 0; i <= 25; ++i) {
buttons[i] = new Button(Character.toString(letters[i]));
buttons[i].addActionListener(actionListener);
panel1.add(buttons[i]);
}
Here as you can see the listener is called, and I want to find out which button I'm clicking. Is there a way to do that?
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getSource());
}
};
I need some way to find the button in the array.
try this
ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
System.out.println(actionEvent.getActionCommand());
}
};
In order to get label, try this.
ActionListener actionListener = new ActionListener()
{
public void actionPerformed(ActionEvent actionEvent) {
JButton button = (JButton)actionEvent.getSource();
String label = button.getLabel(); //Deprecated
String label2 = button.getText();
}
};
ActionEvent has a method getActionCommand() that will get a JButton's actionCommand String. This is usually it's text as well (for JButtons).
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
l1.setText("");//name of level what you want
t1.setText(null);//text field what you want
t2.setText(null);//text field what you want
}

why doesnt my actionListener work with my jcomboBox

I know I'm missing something very simplem but for the life of me I can't see it. All I want to do is get "Paris" from the combo box, and when the button is pressed, show that "Paris" is selected.
public class assignment2try2 implements ActionListener {
private JComboBox HolidayLocation;
private JComboBox HolidayDuration;
private JButton PriceCheck;
public static void main(String[] args) {
JLabel Location = new JLabel(" Where do you want to go ? ");
String[] HolidayLocations = {" ","Paris", "Crete", "Croatia"};
JComboBox<String> LocationBox = new JComboBox<String>(HolidayLocations);
LocationBox.setEditable(false);
LocationBox.setPreferredSize(new Dimension( 160, 20 ));
//LocationBox.setSelectedIndex(4);
LocationBox.addActionListener(LocationBox);
JButton PriceCheck = new JButton("Check Availability");
PriceCheck.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.out.println("button works");
//if(LocationBox.getSelectedItem().equals(HolidayLocations))
{
//System.out.println("paris selected");
}
}
});
}
}
EDIT: I just now noticed that your class implements ActionListener. With the below solution, you can remove the implements-statement from your code.
To fix your issues with the String having to be final, make a private class:
private class MyListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
System.out.println(locationBox.getSelectedItem() + " selected.");
}
}
Then, replace
PriceCheck.addActionListener(new ActionListener() { ... });
with
PriceCheck.addActionListener(new MyListener());
This should be able to print out the selected value after the button is pressed.
Note: I changed your variable name from LocationBox to locationBox to comply with naming conventions.

Use method as event listener instead of class

I always make an event listener for buttons and such like this:
class MyClass implements extends JPanel implements ActionListener{
JButton btn1, btn2, btn3;
public Myclass(){
....
btn1 = new JButton("button 1");
btn1.addActionListener(this);
....
}
public void actionPerformed(ActionEvent e) {
Object action = e.getSource();
if(action = btn1){
functionForBTN1();
}
else if(action = btn2){
functionForBTN2();
}
else if(action = btn3){
functionForBTN3();
}
}
public void functionForBTN1(){...}
public void functionForBTN2(){...}
public void functionForBTN3(){...}
}
Is it possible to direct the event directly to a method instead of the actionPerformed() method? something like (pseudo-code):
class MyClass implements extends JPanel implements ActionListener{
JButton btn1, btn2, btn3;
public Myclass(){
....
btn1 = new JButton("button 1");
btn1.addActionListener(this.functionForBTN1());
....
}
public void functionForBTN1(){...}
public void functionForBTN2(){...}
public void functionForBTN3(){...}
}
If you're using Java 8, you can accomplish this using a lambda expression.
btn1.addActionListener(e -> this.functionForBTN1());
Prior to Java 8, you could create an anonymous ActionListener to acomplish the same task.
btn1.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e){
this.functionForBTN1();
}
});
You can use anonymous classes:
btn1.addActionListener(new ActionListener (){
public void actionPerformed(ActionEvent e) {
// ....
}
});
However, if you want to add it like you did in your second snippet, you can do something like:
final ActionListener listener = new ActionListener() {
#Override
public void actionPerformed(final ActionEvent e) {
if (e.getSource() == btn1) {
//...
} else if (e.getSource() == btn2) {
//...
}
}
};
And then:
btn1.addActionListener(listener);
btn2.addActionListener(listener);
I personally prefer anonymous classes as long as they're readable and not too long.
As Maroun Maroun said an anonymous class is a good idea. With java-8 you could also use a lamdba which makes the code slightly nicer;
btn1.addActionListener(event -> functionForBTN1());

How to make two JButtons do separate actions

Everytime I press cancel or save on the UI it always executes both of the buttons. I've tried countless ways to make it listen to the if statements in the actionperformed block, but it seems to ignore it. I need it so that if I click save it only executes onSave() and cancel for onCancel(). Thanks for your time
public class EditTagPanel extends AbstractTagPanel implements ActionListener {
TagPanelEventListener tagPanelEventListener;
JButton save;
JButton cancel;
public EditTagPanel(ID3v1 id3v1Tag) {
super(id3v1Tag);
}
#Override
protected void configureActionFields() {
JPanel editOptionsPanel = new JPanel(new FlowLayout());
save = new JButton("Save");
save.addActionListener(this);
editOptionsPanel.add(save);
cancel = new JButton("Cancel");
cancel.addActionListener(this);
editOptionsPanel.add(cancel);
this.add(editOptionsPanel, BorderLayout.PAGE_END);
}
public void addTagPanelEventListener(TagPanelEventListener tagPanelEvent) {
this.tagPanelEventListener = tagPanelEvent;
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(save));
{
tagPanelEventListener.onSave(getId3v1Tag());
}
if(e.getSource().equals(cancel));
{
tagPanelEventListener.onCancel();
}
}
Just remove:
;
after each if-statment in your actionPerformed() method, like next:
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(save)) {
tagPanelEventListener.onSave(getId3v1Tag());
}
if (e.getSource().equals(cancel)) {
tagPanelEventListener.onCancel();
}
}

Categories