Dispatching Mouse Events

How can I pass or send a mousedown to a choice menu when a button is pressed?

Sending an event to an AWT component is as simple as creating an event and dispatching it with dispatchEvent(), which is definedin java.awt.Component. However, you will find limited success using this technique with java.awt components, because user-dispatched events do not always have the desired effect on these native peer-based components. Unless you are building applets, I recommend that you stop using java.awt components and switch over completely to javax.swing components. They are more flexible and consistent in their range of allowable behavior. The following example demonstrates how to pop up a choice menu when a button is pressed using Swing components. There is no need to dispatch an event because JComboBox provides the convenientshowPopup() method.

import javax.swing.*;import java.awt.*;import java.awt.event.*;/*** * This program demonstrates how to make a choice menu pop up when a * button is clicked.  It uses Swing components because peer-based AWT * components will not reliably respond to user-dispatched events. ***/public class EventExample extends JFrame {  private JButton __button;  private JComboBox __choice;  public EventExample() {    __button = new JButton("Activate");    __choice = new JComboBox();    __choice.addItem("One");    __choice.addItem("Two");    __choice.addItem("Three");    __button.addActionListener(new ActionListener() {      public void actionPerformed(ActionEvent e) {	__choice.requestFocus();	__choice.showPopup();      }    });    getContentPane().add(__choice, BorderLayout.CENTER);    getContentPane().add(__button, BorderLayout.SOUTH);  }  public static void main(String[] args) {    Frame frame;    WindowListener exitListener;    exitListener = new WindowAdapter() {      public void windowClosing(WindowEvent e) {        Window window = e.getWindow();        window.setVisible(false);        window.dispose();        System.exit(0);      }    };    frame = new EventExample();    frame.addWindowListener(exitListener);    frame.pack();    frame.setVisible(true);  }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin


Recent Articles: