按鈕點選事件(java)
阿新 • • 發佈:2019-01-31
在java中,都將事件的相關資訊封裝在一個事件物件中,所有的事件物件都最終派生於java.util.EventObje
類。當然,每個事件型別還有子類,例如ActionEvent和WindowEvent。不同的事件源可以產生不同類別
的事件。例如,按鈕可以傳送一個ActionEvent物件,而視窗可以傳送WindowEvent物件。
下面以一個響應按鈕點選事件簡單示例來說明所需要知道的所有細節。在這個示例中,想要在一個面板中
放置三個按鈕,新增三個監聽器物件用來作為按鈕的動作監聽器。只要使用者點選面板上的任何一個按鈕,
相關的監聽器物件就會接收到一個Action Event物件,他表示有個按鈕被點選了。在示例程式中,監聽器
物件將改變面
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.*;
- publicclass Main {
- publicstaticvoid main(String[] args)
- {
- EventQueue.invokeLater(()->{
- JFrame frame=new ButtonFrame();
-
frame.setTitle("ListenerTest");
- frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- frame.setVisible(true);
- }
- );
- }
- }
- class ButtonFrame extends JFrame {
- private JPanel buttonPanel;
- public ButtonFrame(){
- setSize(300,200);
-
//create buttons
- JButton yellowButton = new JButton("Yellow");
- JButton blueButton=new JButton("Blue");
- JButton redButton=new JButton("Red");
- /*
- 由於不能將元件加入到JFrame中,我們使用JPanel(一個面板容器類,可以放按鈕、圖片、標籤等)作為中間容器,
- 然後再將JPanel置為JFrame的內容
- */
- buttonPanel=new JPanel();
- //add buttons to panel
- buttonPanel.add(yellowButton);
- buttonPanel.add(blueButton);
- buttonPanel.add(redButton);
- //add panel to frame
- add(buttonPanel);
- //create button actions
- ColorAction yellowAction = new ColorAction(Color.YELLOW);
- ColorAction blueAction = new ColorAction(Color.BLUE);
- ColorAction redAction = new ColorAction(Color.RED);
- //associate actions with buttons
- yellowButton.addActionListener(yellowAction);
- blueButton.addActionListener(blueAction);
- redButton.addActionListener(redAction);
- }
- //當按鈕被點選時,將面板的顏色設定為指定的顏色,這個顏色儲存在監聽器類中
- privateclass ColorAction implements ActionListener{
- private Color backgroundColor;
- public ColorAction(Color c){
- backgroundColor = c;
- }
- publicvoid actionPerformed(ActionEvent event){
- //ActionEvent對應按鈕點選、選單選擇、選擇列表項或在文字框中ENTER
- buttonPanel.setBackground((backgroundColor));
- }
- }
- }
方法就會被呼叫。這個物件的backgroundColor例項域被設定為Color.YELLOW,現在就將面板的背景色設
置為黃色了