Java/Event/Event Queue

Материал из Java эксперт
Перейти к: навигация, поиск

ActionEvent.getActionCommand()

   <source lang="java">

import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; class ButtonDemo implements ActionListener {

 JButton jbtnA = new JButton("Alpha");
 JButton jbtnB = new JButton("Beta");
 ButtonDemo() {
   JFrame jfrm = new JFrame("A Button Example");
   jfrm.setLayout(new FlowLayout());
   jfrm.setSize(220, 90);
   jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   jbtnA.addActionListener(this);
   jbtnB.addActionListener(this);
   jfrm.add(jbtnA);
   jfrm.add(jbtnB);
   jfrm.setVisible(true);
 }
 public void actionPerformed(ActionEvent ae) {
   String ac = ae.getActionCommand();
   if (ac.equals("Alpha")) {
     if (jbtnB.isEnabled()) {
       System.out.println("Alpha pressed. Beta is disabled.");
       jbtnB.setEnabled(false);
     } else {
       System.out.println("Alpha pressed. Beta is enabled.");
       jbtnB.setEnabled(true);
     }
   } else if (ac.equals("Beta"))
     System.out.println("Beta pressed.");
 }
 public static void main(String args[]) {
   new ButtonDemo();
 }

}

 </source>
   
  
 
  



Adding an InputMap to a Component

   <source lang="java">

import javax.swing.InputMap; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   InputMap inputMap = new InputMap();
   inputMap.put(KeyStroke.getKeyStroke("F2"), "actionName");
   JButton component = new JButton("button");
   
   inputMap.setParent(component.getInputMap(JComponent.WHEN_FOCUSED));
   component.setInputMap(JComponent.WHEN_FOCUSED, inputMap);
 }

}

 </source>
   
  
 
  



Event object has information about an event, that has happened.

   <source lang="java">

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class EventObject {

 public static void main(String[] args) {
   JFrame f = new JFrame();
   JButton ok = new JButton("Ok");
   ok.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent event) {
       Calendar cal = Calendar.getInstance();
       cal.setTimeInMillis(event.getWhen());
       Locale locale = Locale.getDefault();
       String s = DateFormat.getTimeInstance(DateFormat.SHORT, locale).format(new Date());
       if (event.getID() == ActionEvent.ACTION_PERFORMED)
         System.out.println(" Event Id: ACTION_PERFORMED");
       System.out.println(" Time: " + s);
       String source = event.getSource().getClass().getName();
       System.out.println(" Source: " + source);
       int mod = event.getModifiers();
       if ((mod & ActionEvent.ALT_MASK) > 0)
         System.out.println("Alt ");
       if ((mod & ActionEvent.SHIFT_MASK) > 0)
         System.out.println("Shift ");
       if ((mod & ActionEvent.META_MASK) > 0)
         System.out.println("Meta ");
       if ((mod & ActionEvent.CTRL_MASK) > 0)
         System.out.println("Ctrl ");
     }
   });
   f.add(ok);
   f.setSize(420, 250);
   f.setLocationRelativeTo(null);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}

 </source>
   
  
 
  



Event source and listener

   <source lang="java">

import java.util.ArrayList; import java.util.EventListener; import java.util.EventObject; abstract class TestEventSource {

 public abstract void addListener(TestEventListener l);
 public abstract void removeListener(TestEventListener l);
 public abstract void fireEvent(java.util.EventObject o);
 public void test() {
   addListener(new TestEventListener("A"));
   fireEvent(new java.util.EventObject(this));
 }

} class TestEventListener implements EventListener {

 String id;
 public TestEventListener(String id) {
   this.id = id;
 }
 public void handleEvent(EventObject o) {
   System.out.println(id + " called");
   if (id.equals("C")) {
     ((TestEventSource) o.getSource()).removeListener(this);
   }
 }

} public class Main extends TestEventSource {

 ArrayList listeners = new ArrayList();
 public void addListener(TestEventListener l) {
   listeners.add(l);
 }
 public void removeListener(TestEventListener l) {
   listeners.remove(l);
 }
 public void fireEvent(EventObject o) {
   for (int i = 0; i < listeners.size(); i++) {
     TestEventListener l = (TestEventListener) listeners.get(i);
     l.handleEvent(o);
   }
 }
 public static void main(String[] args) {
   Main pfles = new Main();
   pfles.test();
 }

}

 </source>
   
  
 
  



int java.awt.event.WindowEvent.WINDOW_OPENED

   <source lang="java">

import java.awt.AWTEvent; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ruponentEvent; import java.awt.event.WindowEvent; import javax.swing.AbstractAction; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; public class Main implements AWTEventListener {

 public void eventDispatched(AWTEvent evt) {
   if (evt.getID() == WindowEvent.WINDOW_OPENED) {
     ComponentEvent cev = (ComponentEvent) evt;
     if (cev.getComponent() instanceof JFrame) {
       System.out.println("event: " + evt);
       JFrame frame = (JFrame) cev.getComponent();
       loadSettings(frame);
     }
   }
 }
 public static void loadSettings(JFrame frame) {
   System.out.println("loading");
 }
 public static void saveSettings() {
   System.out.println("saving");
 }
 public static void main(String[] args) throws Exception {
   Toolkit tk = Toolkit.getDefaultToolkit();
   final Main main = new Main();
   tk.addAWTEventListener(main, AWTEvent.WINDOW_EVENT_MASK);
   final JFrame frame = new JFrame("");
   frame.setName("your frame");
   JMenuBar mb = new JMenuBar();
   JMenu menu = new JMenu("File");
   menu.add(new AbstractAction("Quit") {
     public void actionPerformed(ActionEvent evt) {
       try {
         main.saveSettings();
         System.exit(0);
       } catch (Exception ex) {
         System.out.println(ex);
       }
     }
   });
   mb.add(menu);
   frame.setJMenuBar(mb);
   frame.pack();
   frame.setVisible(true);
 }

}

 </source>
   
  
 
  



JComponent.WHEN_IN_FOCUSED_WINDOW

   <source lang="java">

import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.KeyStroke; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton();
   MyAction action = new MyAction();
   component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F2"),
       action.getValue(Action.NAME));
 }

} class MyAction extends AbstractAction {

 public MyAction() {
   super("my action");
 }
 public void actionPerformed(ActionEvent e) {
   System.out.println("hi");
 }

}

 </source>
   
  
 
  



Multiple sources: A listener can be plugged into several sources.

   <source lang="java">

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; class ButtonListener implements ActionListener {

 public void actionPerformed(ActionEvent e) {
   JButton o = (JButton) e.getSource();
   String label = o.getText();
   System.out.println(label + " button clicked");
 }

} public class MultipleSources {

 public static void main(String[] args) {
   JPanel panel = new JPanel();
   JButton close = new JButton("Close");
   close.addActionListener(new ButtonListener());
   JButton open = new JButton("Open");
   open.addActionListener(new ButtonListener());
   JButton find = new JButton("Find");
   find.addActionListener(new ButtonListener());
   JButton save = new JButton("Save");
   save.addActionListener(new ButtonListener());
   panel.add(close);
   panel.add(open);
   panel.add(find);
   panel.add(save);
   JFrame f = new JFrame();
   f.add(panel);
   f.setSize(400, 300);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }

}

 </source>
   
  
 
  



Register action

   <source lang="java">

import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JButton; public class Main {

 public static void main(String[] argv) throws Exception {
   JButton component = new JButton();
   MyAction action = new MyAction();
   component.getActionMap().put(action.getValue(Action.NAME), action);
 }

} class MyAction extends AbstractAction {

 public MyAction() {
   super("my action");
 }
 public void actionPerformed(ActionEvent e) {
   System.out.println("hi");
 }

}

 </source>
   
  
 
  



Register several listeners for one event.

   <source lang="java">

import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; public class MultipleListeners {

 JLabel statusbar = new JLabel("0");
 JSpinner spinner = new JSpinner();
 static int count = 0;
 class ButtonListener1 implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     Integer val = (Integer) spinner.getValue();
     spinner.setValue(++val);
   }
 }
 class ButtonListener2 implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     statusbar.setText(Integer.toString(++count));
   }
 }
 public MultipleListeners() {
   JPanel panel = new JPanel();
   JButton add = new JButton("+");
   add.addActionListener(new ButtonListener1());
   add.addActionListener(new ButtonListener2());
   panel.add(add);
   panel.add(spinner);
   JFrame f = new JFrame();
   f.add(panel);
   f.add(statusbar, BorderLayout.SOUTH);
   f.setSize(300, 200);
   f.setLocationRelativeTo(null);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }
 public static void main(String[] args) {
   new MultipleListeners();
 }

}

 </source>
   
  
 
  



Use the Event queue to retrieve event

   <source lang="java">

import java.awt.AWTEvent; import java.awt.Container; import java.awt.EventQueue; import java.awt.Frame; import java.awt.Graphics; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; public class EventQueuePanel extends JPanel implements ActionListener {

 EventQueuePanel() {
   JButton button = new JButton("Draw line");
   add(button);
   button.addActionListener(this);
 }
 public void actionPerformed(ActionEvent evt) {
   Graphics g = getGraphics();
   displayPrompt(g, "Click to chooose the first point");
   Point p = getClick();
   g.drawOval(p.x - 2, p.y - 2, 4, 4);
   displayPrompt(g, "Click to choose the second point");
   Point q = getClick();
   g.drawOval(q.x - 2, q.y - 2, 4, 4);
   g.drawLine(p.x, p.y, q.x, q.y);
   displayPrompt(g, "Done! Press button the start again.");
   g.dispose();
 }
 public void displayPrompt(Graphics g, String s) {
   y += 20;
   g.drawString(s, 0, y);
 }
 public Point getClick() {
   EventQueue eq = Toolkit.getDefaultToolkit().getSystemEventQueue();
   while (true) {
     try {
       AWTEvent evt = eq.getNextEvent();
       if (evt.getID() == MouseEvent.MOUSE_PRESSED) {
         MouseEvent mevt = (MouseEvent) evt;
         Point p = mevt.getPoint();
         Point top = getRootPane().getLocation();
         p.x -= top.x;
         p.y -= top.y;
         return p;
       }
     } catch (InterruptedException e) {
     }
   }
 }
 private int y = 60;
 public static void main(String[] args) {
   JFrame frame = new JFrame();
   frame.setTitle("EventQueueTest");
   frame.setSize(300, 200);
   frame.addWindowListener(new WindowAdapter() {
     public void windowClosing(WindowEvent e) {
       System.exit(0);
     }
   });
   Container contentPane = frame.getContentPane();
   contentPane.add(new EventQueuePanel());
   frame.show();
 }

}


 </source>
   
  
 
  



Using an inner ActionListener class.

   <source lang="java">

import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; public class InnerClass {

 class ButtonListener implements ActionListener {
   public void actionPerformed(ActionEvent e) {
     System.exit(0);
   }
 }
 public InnerClass() {
   JButton close = new JButton("Close");
   ButtonListener listener = new ButtonListener();
   close.addActionListener(listener);
   JFrame f = new JFrame();
   f.add(close);
   f.setSize(300, 200);
   f.setLocationRelativeTo(null);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.setVisible(true);
 }
 public static void main(String[] args) {
   new InnerClass();
 }

}

 </source>
   
  
 
  



void java.awt.Toolkit.addAWTEventListener(AWTEventListener listener, long eventMask)

   <source lang="java">

import java.awt.AWTEvent; import java.awt.Toolkit; import java.awt.event.AWTEventListener; import java.awt.event.ActionEvent; import java.awt.event.ruponentEvent; import java.awt.event.WindowEvent; import javax.swing.AbstractAction; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; public class Main implements AWTEventListener {

 public void eventDispatched(AWTEvent evt) {
   if (evt.getID() == WindowEvent.WINDOW_OPENED) {
     ComponentEvent cev = (ComponentEvent) evt;
     if (cev.getComponent() instanceof JFrame) {
       System.out.println("event: " + evt);
       JFrame frame = (JFrame) cev.getComponent();
       loadSettings(frame);
     }
   }
 }
 public static void loadSettings(JFrame frame) {
   System.out.println("loading");
 }
 public static void saveSettings() {
   System.out.println("saving");
 }
 public static void main(String[] args) throws Exception {
   Toolkit tk = Toolkit.getDefaultToolkit();
   final Main main = new Main();
   tk.addAWTEventListener(main, AWTEvent.WINDOW_EVENT_MASK);
   final JFrame frame = new JFrame("");
   frame.setName("your frame");
   JMenuBar mb = new JMenuBar();
   JMenu menu = new JMenu("File");
   menu.add(new AbstractAction("Quit") {
     public void actionPerformed(ActionEvent evt) {
       try {
         main.saveSettings();
         System.exit(0);
       } catch (Exception ex) {
         System.out.println(ex);
       }
     }
   });
   mb.add(menu);
   frame.setJMenuBar(mb);
   frame.pack();
   frame.setVisible(true);
 }

}

 </source>