Java中的awt包提供了丰富的用户界面组件。重要的是,Java的跨平台性使用awt包可以在Windows,MacOS等平台创建桌面软件。本篇博客总结Button控件的简单使用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| 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) { System.out.println(e.getActionCommand()); } }
|
与addActionCommand方法对应,Button类中还有一些移除监听与获取监听者的方法,如下:
1 2 3 4 5 6
| public synchronized void removeActionListener(ActionListener l);
public synchronized ActionListener[] getActionListeners();
public <T extends EventListener> T[] getListeners(Class<T> listenerType);
|
ActionEvent类中定义了交互行为的一些特征,示例如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class MyActionListener implements ActionListener{ @Override public void actionPerformed(ActionEvent e) { System.out.println(e.getWhen()); System.out.println(e.getModifiers()); System.out.println(e.getSource()); System.out.println(e.getActionCommand()); } }
|
getModifiers方法获取事件的模式,返回值定义如下:
1 2 3 4 5 6 7 8
| public static final int SHIFT_MASK = Event.SHIFT_MASK;
public static final int CTRL_MASK = Event.CTRL_MASK;
public static final int META_MASK = Event.META_MASK;
public static final int ALT_MASK = Event.ALT_MASK;
|