【问题标题】:How is action on JButton being invoked in this code?在此代码中如何调用对 JButton 的操作?
【发布时间】:2015-01-29 14:28:25
【问题描述】:

我无法理解 actionListener 在以下代码中的使用方式以及 addWindowListener 方法在以下代码中的作用:

请帮帮我。

public class SwingListenerDemo {
  private JFrame mainFrame;
  private JLabel statusLabel;

  public SwingListenerDemo(){
    prepareGUI();           }

  public static void main(String[] args){
   SwingListenerDemo  swingListenerDemo = new SwingListenerDemo();  
   swingListenerDemo.showActionListenerDemo();}

   private void prepareGUI(){
     mainFrame = new JFrame("Java SWING Examples");
     mainFrame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent windowEvent){
        System.exit(0);
     }        
  });    

    mainFrame.setVisible(true);  
  }

   private void showActionListenerDemo(){

      JButton okButton = new JButton("OK");

    okButton.addActionListener(new CustomActionListener());        
    mainFrame.add(okButton);

    mainFrame.setVisible(true);         }

   class CustomActionListener implements ActionListener{
           public void actionPerformed(ActionEvent e) {
             statusLabel.setText("Ok Button Clicked.");
                                                      }
                                                       }    
    }

【问题讨论】:

  • 在您最喜欢的搜索引擎中分别为每个“jbutton actionlistener windowlistener”添加“教程”,这应该可以回答您的问题。
  • @Andrew Thompson:完全正确.. 我想这个论坛是针对您在文档中找不到的复杂案例,但不是针对基本问题。很多人都很懒,在一些论坛发垃圾邮件更舒服。

标签: java swing jbutton actionlistener windowlistener


【解决方案1】:
  • 当您单击确定按钮时,您的actionPerformed 方法将被调用,因为您将确定按钮上的回调注册为okButton.addActionListener(new CustomActionListener());
  • 当您从右上角的“X”按钮关闭 awing 窗口时,您的程序将退出并返回代码 0,这就是您的窗口侦听器在 windowClosing 方法中所做的事情。

【讨论】:

  • 感谢您的回答,但我不明白 System.exit(0) 是什么;在 windowClosing 方法中做。请帮助我..
  • this 它将终止你的java进程,返回状态为0。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多