Java中的awt包提供了豐富的用戶界面組件。重要的是,Java的跨平臺性使用awt包能夠在Windows,MacOS等平臺建立桌面軟件。本篇博客總結Button控件的簡單使用。java
package App; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class ButtonTest { public static void main(String[] args ) { //建立面板 Frame frame = new Frame("BUTTON"); //建立按鈕 Button button1 = new Button(); //設置按鈕標題 button1.setLabel("按鈕"); //設置按鈕標記 用在觸發方法中分區按鈕 button1.setActionCommand("tag1"); //獲取按鈕標題 System.out.println(button1.getLabel()); //添加按鈕 frame.add(button1); //添加交互監聽 button1.addActionListener(new MyActionListener()); frame.pack(); frame.show(); } } class MyActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub //這裏能夠取到按鈕設置的actionCommand值 System.out.println(e.getActionCommand()); } }
與addActionCommand方法對應,Button類中還有一些移除監聽與獲取監聽者的方法,以下:數組
//移除一個監聽者 public synchronized void removeActionListener(ActionListener l); //獲取監聽者列表 public synchronized ActionListener[] getActionListeners(); //獲取監聽者列表 泛型數組 public <T extends EventListener> T[] getListeners(Class<T> listenerType);
ActionEvent類中定義了交互行爲的一些特徵,示例以下:ide
class MyActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub //獲取觸發時間 System.out.println(e.getWhen()); //獲取觸發模式 System.out.println(e.getModifiers()); //獲取觸發事件的控件 此處爲Button按鈕 System.out.println(e.getSource()); //獲取關聯的actionCommand值 System.out.println(e.getActionCommand()); } }
getModifiers方法獲取事件的模式,返回值定義以下:spa
//按住shift鍵點擊按鈕 public static final int SHIFT_MASK = Event.SHIFT_MASK; //按住ctrl鍵點擊按鈕 public static final int CTRL_MASK = Event.CTRL_MASK; //按住meta鍵點擊按鈕 public static final int META_MASK = Event.META_MASK; //按住alt鍵點擊按鈕 public static final int ALT_MASK = Event.ALT_MASK;