如何在此代码中调用JButton上的操作?

时间:2015-01-29 14:28:26

标签: java swing jbutton actionlistener windowlistener

我无法理解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.");
                                                      }
                                                       }    
    }

1 个答案:

答案 0 :(得分:1)

  • 点击“确定”按钮后,当您在“确定”按钮上注册回调时,actionPerformed方法将被调用okButton.addActionListener(new CustomActionListener());
  • 当您从右上方关闭您的窗户时,X' X'按钮,你的程序将退出,返回代码为0,这是你的窗口监听器在windowClosing方法中所做的事情。