devxlogo

Dispatching Mouse Events

Dispatching Mouse Events

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

Answer:
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);  }}
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist