1. 程式人生 > >按鈕點選事件(java)

按鈕點選事件(java)

在java中,都將事件的相關資訊封裝在一個事件物件中,所有的事件物件都最終派生於java.util.EventObje
類。當然,每個事件型別還有子類,例如ActionEvent和WindowEvent。不同的事件源可以產生不同類別
的事件。例如,按鈕可以傳送一個ActionEvent物件,而視窗可以傳送WindowEvent物件。

下面以一個響應按鈕點選事件簡單示例來說明所需要知道的所有細節。在這個示例中,想要在一個面板中
放置
三個按鈕,新增三個監聽器物件用來作為按鈕的動作監聽器。只要使用者點選面板上的任何一個按鈕,
相關的監
聽器物件就會接收到一個Action Event物件,他表示有個按鈕被點選了。在示例程式中,監聽器
物件將改變面

板的背景顏色。

  1. import java.awt.*;  
  2. import java.awt.event.*;  
  3. import javax.swing.*;  
  4. publicclass Main {  
  5.     publicstaticvoid main(String[] args)  
  6.     {  
  7.         EventQueue.invokeLater(()->{  
  8.                     JFrame frame=new ButtonFrame();  
  9.                     frame.setTitle("ListenerTest");  
  10.                     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  11.                     frame.setVisible(true);  
  12.                 }  
  13.         );  
  14.     }  
  15. }  
  16. class ButtonFrame extends JFrame {  
  17.     private JPanel buttonPanel;  
  18.     public ButtonFrame(){  
  19.         setSize(300,200);  
  20.         //create buttons
  21.         JButton yellowButton = new JButton("Yellow");  
  22.         JButton blueButton=new JButton("Blue");  
  23.         JButton redButton=new JButton("Red");  
  24. /* 
  25. 由於不能將元件加入到JFrame中,我們使用JPanel(一個面板容器類,可以放按鈕、圖片、標籤等)作為中間容器, 
  26. 然後再將JPanel置為JFrame的內容 
  27.  */
  28.         buttonPanel=new JPanel();  
  29.         //add buttons to panel
  30.         buttonPanel.add(yellowButton);  
  31.         buttonPanel.add(blueButton);  
  32.         buttonPanel.add(redButton);  
  33.         //add panel to frame
  34.         add(buttonPanel);  
  35.         //create button actions
  36.         ColorAction yellowAction = new ColorAction(Color.YELLOW);  
  37.         ColorAction blueAction = new ColorAction(Color.BLUE);  
  38.         ColorAction redAction = new ColorAction(Color.RED);  
  39.         //associate actions with buttons
  40.         yellowButton.addActionListener(yellowAction);  
  41.         blueButton.addActionListener(blueAction);  
  42.         redButton.addActionListener(redAction);  
  43.     }  
  44.     //當按鈕被點選時,將面板的顏色設定為指定的顏色,這個顏色儲存在監聽器類中
  45.     privateclass ColorAction implements ActionListener{  
  46.         private Color backgroundColor;  
  47.         public ColorAction(Color c){  
  48.             backgroundColor = c;  
  49.         }  
  50.         publicvoid actionPerformed(ActionEvent event){  
  51.             //ActionEvent對應按鈕點選、選單選擇、選擇列表項或在文字框中ENTER
  52.             buttonPanel.setBackground((backgroundColor));  
  53.         }  
  54.     }  
  55. }  
例如,如果在標有“Yellow”的按鈕上點選了一下,此按鈕繫結的事件yellowAction物件的actionPerformed
方法就會被呼叫。這個物件的backgroundColor例項域被設定為Color.YELLOW,現在就將面板的背景色設
置為黃色了