Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: AWT
Expertise: Beginner
May 2, 1999

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 defined in 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 convenient showPopup() 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);
  }

}

DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap