我怎么知道另一个 class 的 JButton 被选中了?

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

我创建了一个 class,它在另一个 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);
   .
   . 
   .
            }
            });
}

这是我的新文章class:


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

所以当我单击 WindowManege class 的新菜单项时,NewArticle window 将出现,当我单击 NewArticle window 中的添加按钮时,此 window 将关闭,我的旧 window (WindowManege class) 会发生一些变化 我的问题是我应该在 WindowManege 中设置什么条件来单击或选择 NewArticle 的添加按钮。

我不确定你想说什么,但如果你问的话。你如何让程序知道当一个特定的按钮被点击时要做什么那么你需要在action Performed方法下添加这行代码。

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

}

我们使用条件为 e.getSource == (Your button's name) 的 if 语句,因此它知道在单击特定按钮时要做什么。

示例:

JButton button = new JButton("Button");
button.addActionListener(new buttonTestClass());

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

注意:由于它来自另一个 class,因此您应该将按钮 public 设为静态,以便您可以在另一个 class 中访问它。此外,由于要从另一个 class 调用它,您说 classname.button。示例:testButtonClass.button