Search code examples
javaswingclassjframeactionlistener

How can i know that a JButton of another class is selected?


i created a class that implements an interface in another class :

public class WindowManege extends JFrame implements ActionListener,NouvelArticle.NouvelArticleEvent{
NewArticle nv;
JMenuItem new= new JMenuItem("new");
 new.addActionListener(new ActionListener() { 
            public void actionPerformed(ActionEvent ev) {
             nv.setVisible(true);
             nv.setAlwaysOnTop(true);
   .
   . 
   .
            }
            });
}

and this is my NewArticle class:


public class NewArticle extends JFrame {
  .
  .
  .
 public NewArticle(){
  .
  .
  .
add.addActionListener(new ActionListener() {
         
         public void actionPerformed(ActionEvent e) {
             
     .
     . 
     .               
          
         }
      });
        
    }

so when i click at new menu item of WindowManege class, the NewArticle window will appear , and when i click at add button in NewArticle window, this window will close and something will change in my old window (WindowManege class) my question is what condition i should make in WindowManege that the add button of NewArticle is clicked or selected.


Solution

  • I'm not sure what are you trying to say but if you're asking. How do you make the program know what to do when a specific button is clicked then you need to add this line of code under the action Performed method.

    if(e.getSource == (Your Button's Name) { 
       // Put what you want your button to do here
    
    }
    

    We use an if statement with the condition of e.getSource == (Your button's name) so it knows what to do if that specific button was clicked.

    Example:

    JButton button = new JButton("Button");
    button.addActionListener(new buttonTestClass());
    
    public void actionPerformed(ActionEvent e) {
      if(e.getSource == button) {
          System.out.println("Button clicked")
      }
    }
    
    

    Note: Since it's from another class you should make the button public and static so you can access it in the other class. Also, since to call it from another class you say classname.button. Example: testButtonClass.button