-1

good day everyone. I have many java files in a project in netbeans. One file is named mainFile while some are addSale, addAttendance. In my mainFile.java, I created an actionPerformed method to check if a button is clicked. But the buttons that I want to checked if clicked is on the other java files.

I've added this code in my mainFile.java

AddSales addSaleButton;
  Login logButton;

  public void actionPerformed(ActionEvent ae){
    if (ae.getSource() == addSaleButton.getButton()){
      System.out.print("sample add");
    }else if (ae.getSource() == logButton.getButton()){
      System.out.print("sample log");
    }
  } 

  public void setButtonAction(Action action) {
      (addSaleButton.getButton()).setAction(action);
   }

then I added this in my addSales.java

public JButton getButton() {
        return confirmAddSales;
    }
Rocky
  • 429
  • 1
  • 9
  • 26
  • Did you add an ActionListener to the confirmAddSales button from within the instance of your other class? – MadProgrammer May 08 '14 at 21:25
  • yes. @MadProgrammer the confirmAddSales button adds a new record in the table "sales" in my database. I want to check if a button is clicked from another java classes for it will insert a new record in the "log" table in my database. – Rocky May 08 '14 at 21:29
  • Use the actionCommand property if the JButton instead – MadProgrammer May 08 '14 at 21:37
  • @MadProgrammer the confirmAddSales button has its own actionlistener in the AddSales.java where it belong. I added again a listener from within the instane of my MainFile.java Is this correct? – Rocky May 08 '14 at 21:50
  • @user3615601: yes you can do this. Again, the devil's in the details -- are you using the right references? Again, consider creating and posting a minimal example. – Hovercraft Full Of Eels May 08 '14 at 21:52

2 Answers2

2

Yes this is possible and is often done, but the devil is in the details. Often you'll have a Control class that responds to user interaction that is completely separate from the View class, the GUI. Options include:

  • Give the view class a public addButtonXActionListener(ActionListener l) method.
  • Give the view property change listener support, and if it subclasses a Swing component, it automatically has this, and then in your JButton's ActionListener, often an anonymous inner class, notify the listeners of a state change.
  • Give the Ciew class a Control instance variable and set it. Then in the JButton's ActionListener, call the appropriate control method.

Edit
For example, here is a small program with 3 files, 1 for the View that holds the JButton, 1 for the Control, and a 3rd main class just to get things running.

Note that there are two JButtons and they both use 2 different ways of notifying outside classes that they've been pressed.

  1. The View class has a public method, Button 1 has a method, public void setButton1Action(Action action), that allows outside classes to set the Action of button1, The Control then does this, injecting an AbstractAction that notifies the Control of when button1 has been pressed.
  2. The View has an public void addPropertyChangeListener(PropertyChangeListener l) wrapper method that allows outside classes to add in their PropertyChangeListener which then is added to the property change support of the mainPanel object. Then in button2's anonymous inner ActionListener class, the mainPanel's PropertyChangeSupport is asked to notify all listeners of a change in the state of the BUTTON2 property. View then adds a PropertyChangeListener and listens for changes the state of this property and responds.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;

import javax.swing.*;

public class TestButtonPress {
   private static void createAndShowGui() {
      View view = new View();
      Control control = new Control();
      control.setView(view);

      JFrame frame = new JFrame("TestButtonPress");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(view.getMainPanel());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

class View {
   public static final String BUTTON2 = "Button 2";
   private JPanel mainPanel = new JPanel();
   private JButton button1 = new JButton();
   private JButton button2 = new JButton(BUTTON2);

   public View() {
      mainPanel.add(button1);
      mainPanel.add(button2);

      button2.addActionListener(new ActionListener() {

         @Override
         public void actionPerformed(ActionEvent e) {
            mainPanel.firePropertyChange(BUTTON2, false, true);
         }
      });
   }

   public JComponent getMainPanel() {
      return mainPanel;
   }

   public void setButton1Action(Action action) {
      button1.setAction(action);
   }

   public void addPropertyChangeListener(PropertyChangeListener l) {
      mainPanel.addPropertyChangeListener(l);
   }

   public void removePropertyChangeListener(PropertyChangeListener l) {
      mainPanel.removePropertyChangeListener(l);
   }

}

class Control {
   View view;

   public void setView(final View view) {
      this.view = view;
      view.setButton1Action(new ButtonAction());
      view.addPropertyChangeListener(new Button2Listener());
   };

   private class ButtonAction extends AbstractAction {
      public ButtonAction() {
         super("Button 1");
      }

      @Override
      public void actionPerformed(ActionEvent evt) {
         System.out.println(evt.getActionCommand() + " has been pressed!");
      }
   }

   private class Button2Listener implements PropertyChangeListener {
      @Override
      public void propertyChange(PropertyChangeEvent evt) {
         if (View.BUTTON2.equals(evt.getPropertyName())) {
            System.out.println("Button 2 has been pressed!");
         }
      }
   }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • knowing that this is possible. i've tried some samples based from the internet. but it is still not working. – Rocky May 08 '14 at 21:10
  • @user3615601: as I mentioned in my answer, the devil's in the details. I suggest that you try to create the simplest [minimal complete code example](http://stackoverflow.com/help/mcve), one that has two Java classes, one that shows us in a very small program, your problem. – Hovercraft Full Of Eels May 08 '14 at 21:12
  • @user3615601: for example, please see edit to answer. – Hovercraft Full Of Eels May 08 '14 at 21:24
0

From what i understand you want your button in one class and the ActionListener in another. I'm not 100% sure if this is what you want but here is some code for that:

Main class Btn:

package btn;

public class Btn
{
    public static void main(String[] args)
    {
        Frame f = new Frame();
        f.setVisible(true);
    }

}

Button class Button:

package btn;

import javax.swing.JButton;

public class Button extends JButton
{

    public Button()
    {
        super("Hello world");
        this.addActionListener(new ActionListenerClass());
    }
}

ActionListener class ActionListenerClass:

package btn;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ActionListenerClass implements ActionListener
{
    public static int numberOfClicks = 0;

    @Override
    public void actionPerformed(ActionEvent e)
    {
        numberOfClicks++;
        System.out.println("HELLO WORLD!!\n" + "number of times pressed " + numberOfClicks);
    }

}

Frame class Frame:

package btn;

import javax.swing.JFrame;

public class Frame extends JFrame
{
    public Frame()
    {
        super("Hello world test");
        this.setBounds(0, 0, 300, 500);
        this.add(new Button());
        this.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
    }
}

and the output:

    run:
HELLO WORLD!!
number of times pressed 1
HELLO WORLD!!
number of times pressed 2
HELLO WORLD!!
number of times pressed 3
HELLO WORLD!!
number of times pressed 4
BUILD SUCCESSFUL (total time: 3 seconds)

What you are doing here is simply putting the action listener in a separate class and then telling the button to look for the action listener in that class

using this line of code: this.addActionListener(new ActionListenerClass());

Hope this helps, Luke.

EDIT:

try use e.paramString():

this will print something like this:

HELLO WORLD!!
number of times pressed 1
Button: ACTION_PERFORMED,cmd=Hello world,when=1399588160253,modifiers=Button1
BUILD SUCCESSFUL (total time: 2 seconds)

or e.getActionCommand():

this will print the button name:

run:
HELLO WORLD!!
number of times pressed 1
Button: Hello world
BUILD SUCCESSFUL (total time: 4 seconds)

Full actionListener code block:

@Override
    public void actionPerformed(ActionEvent e)
    {
        numberOfClicks++;
        System.out.println("HELLO WORLD!!\n" + "number of times pressed " + numberOfClicks + 
                "\ne.getActionCommand();: " + e.getActionCommand()
        + "\ne.paramString();: " + e.paramString());
    }

output:

run:
HELLO WORLD!!
number of times pressed 1
e.getActionCommand();: Hello world
e.paramString();: ACTION_PERFORMED,cmd=Hello world,when=1399588455144,modifiers=Button1
BUILD SUCCESSFUL (total time: 6 seconds)

SECOND EDIT:

Ok use the getActionCommand(); method and then use a switch stricture to check witch button was pressed.

i have added another button, one called "LOL" and the other called "Hello world" both use the same action listener.

the output from pressing both:

run:
HELLO WORLD!!
number of times pressed 1
e.getActionCommand();: LOL
e.paramString();: ACTION_PERFORMED,cmd=LOL,when=1399590104631,modifiers=Button1
HELLO WORLD!!
number of times pressed 2
e.getActionCommand();: LOL
e.paramString();: ACTION_PERFORMED,cmd=LOL,when=1399590106679,modifiers=Button1
HELLO WORLD!!
number of times pressed 3
e.getActionCommand();: Hello world
e.paramString();: ACTION_PERFORMED,cmd=Hello world,when=1399590107665,modifiers=Button1
HELLO WORLD!!
number of times pressed 4
e.getActionCommand();: Hello world
e.paramString();: ACTION_PERFORMED,cmd=Hello world,when=1399590107780,modifiers=Button1
BUILD SUCCESSFUL (total time: 5 seconds)

now use a switch stricture to tell the difference between the buttons:

@Override
    public void actionPerformed(ActionEvent e)
    {
        numberOfClicks++;
        System.out.println("HELLO WORLD!!\n" + "number of times pressed " + numberOfClicks + 
                "\ne.getActionCommand();: " + e.getActionCommand()
        + "\ne.paramString();: " + e.paramString());

        switch(e.getActionCommand())
        {
            case "LOL":
                System.out.println("Button \"LOL\" was clicked");
                break;
            case "Hello world":
                System.out.println("Button \"Hello world\" was clicked");
                break;
        }
    }

output with switch:

run:
HELLO WORLD!!
number of times pressed 1
e.getActionCommand();: Hello world
e.paramString();: ACTION_PERFORMED,cmd=Hello world,when=1399590324792,modifiers=Button1
Button "Hello world" was clicked
HELLO WORLD!!
number of times pressed 2
e.getActionCommand();: Hello world
e.paramString();: ACTION_PERFORMED,cmd=Hello world,when=1399590324943,modifiers=Button1
Button "Hello world" was clicked
HELLO WORLD!!
number of times pressed 3
e.getActionCommand();: Hello world
e.paramString();: ACTION_PERFORMED,cmd=Hello world,when=1399590325089,modifiers=Button1
Button "Hello world" was clicked
HELLO WORLD!!
number of times pressed 4
e.getActionCommand();: LOL
e.paramString();: ACTION_PERFORMED,cmd=LOL,when=1399590330897,modifiers=Button1
Button "LOL" was clicked
HELLO WORLD!!
number of times pressed 5
e.getActionCommand();: LOL
e.paramString();: ACTION_PERFORMED,cmd=LOL,when=1399590331048,modifiers=Button1
Button "LOL" was clicked
BUILD SUCCESSFUL (total time: 11 seconds)

I hope this answers your question.

Luke Melaia
  • 1,470
  • 14
  • 22
  • What I'm trying to do is check if the button from another java file is clicked. I have many java files in one project in netbeans. All files have their own ActionListener. From my MainFile.java, I want to check if the JButton in AddSales.java is clicked. Is there any basis for this? – Rocky May 08 '14 at 22:25
  • Ok please give a detailed description on what you want? Button name, Button class, Button text? – Luke Melaia May 08 '14 at 22:48
  • I have 3 java files in a package. MainFile.java which contains the main methods that I am using. This java file has its own User Interface with actionlistener that I've created with netbeans. Another file is, AddSale.java, this also has its own UI and actionListeners. AddSale.java has a button name, addConfirmSale. the MainFile.java should detect and print a specific message if the addConfirmSale from AddSale.java is clicked. – Rocky May 08 '14 at 22:56
  • Ok i have modified it to tell the diference between buttons, Hope this helps. – Luke Melaia May 08 '14 at 23:08