call actionperformed method on clicking jmenu - java

can i call actionperformed method with jmenu using swing
i am using the following code
JMenu menu1= new JMenu("File");
MenuBar mb= new MenuBar();
mb.add(menu1);
set JmenuBar(mb)
menu1.addActionListener(this);
public void actionPerformed(ActionEvent ae)
{
JOptionPane.showMessaageDialog(null,"menu clicked");
// but its not working
}
thanks in Advance

The action a JMenu is designed to perform is to open a popup with JMenuItems, it doesn't support doing anything else (and even if it did, it would confuse your users). Custom actions are supposed to be handled by JMenuItems in the popup. Install them with something like:
JMenu menu ..
Action myAction = new AbstractAction("Do XY") {
public void actionPerformed(..) {
// implement doing XY
}
};
menu.add(myAction);

Related

Add JMenuItem to Already Visible JMenu

I am already listening to MenuListener.menuSelected() to know when a JMenu is showing on the screen. Initially, the JMenu has 1 JMenuItem which says "Loading...". After a slow operation, I add JMenuItems to the JMenu. The JMenu continues to show "Loading...". If I select another JMenu and come back, then the JMenu shows the added JMenuItems. How do I cause the added JMenuItems to show up immediately?
Here's the code which reproduces what is happening.
public class AddMenuItem extends JFrame
{
private final JMenu m_menu = new JMenu("Edit");
public static void main(String args[])
{
new AddMenuItem().
setVisible(true);
}
public AddMenuItem()
{
JMenuBar bar;
bar = new JMenuBar();
bar.add(m_menu);
setJMenuBar(bar);
setSize(600, 400);
m_menu.addMenuListener(new MenuListener()
{
#Override
public void menuSelected(MenuEvent e)
{
JMenuItem loading;
loading = new JMenuItem("Loading...");
loading.setEnabled(false);
m_menu.removeAll();
m_menu.add(loading);
// This represents a long running task which updates the menu afterwards
new Timer(5 * 1000, event -> updateMenu()).start();
}
#Override
public void menuDeselected(MenuEvent e)
{
// nothing to do
}
#Override
public void menuCanceled(MenuEvent e)
{
// nothing to do
}
});
}
private void updateMenu()
{
m_menu.removeAll();
m_menu.add(new JMenuItem("1"));
m_menu.add(new JMenuItem("2"));
m_menu.add(new JMenuItem("3"));
m_menu.revalidate();
}
}
It seems that this code example does exactly what I want but I am not sure what they are doing to make the visible menu repaint on the screen.
Initially, the JMenu has 1 JMenuItem which says "Loading...".
Code invoked from a listener executes on the Event Dispatch Thread (EDT). When you execute a long running task, it prevents the EDT from responding to events and repainting the GUI.
So to solve the problem the task started by that menu items needs to execute in a separate Thread. You might want to consider using a SwingWorker. Read the section from the Swing tutorial on Concurrency for more information about the EDT and SwingWorker.
Edit:
The problem is that once I know what to add to the menu, I don't know how to get the menu to show the added JMenuItems
You get the JMenu from the MenuEvent of your MenuListener:
JMenu menu = (JMenu)e.getSource();
menu.add( new JMenuItem( "Loading..." ) );
Edit:
Based on the SSCCE you can do something like:
private void updateMenu()
{
m_menu.removeAll();
m_menu.add(new JMenuItem("1"));
m_menu.add(new JMenuItem("2"));
m_menu.add(new JMenuItem("3"));
JPopupMenu popup = m_menu.getPopupMenu();
popup.pack();
}
But remember because your long running task executes in a separate Thread, you would need to invoke the above code using a SwingUtiltities.invokeLater so that the code is executed on the EDT.
It seems that this code example does exactly what I want but I am not sure what they are doing to make the visible menu repaint on the screen.
I think they are just hiding and showing the menu again.
Instead of doing m_menu.revalidate(), do the following...
if (m_menu.isPopupMenuVisible())
{
m_menu.setPopupMenuVisible(false);
m_menu.setPopupMenuVisible(true);
}

Using ActionListener in separate class

I'm trying to make a separate class for an action listener but I'm not sure how to add the action listener to the menu item. I've been trying a few different things but none of them are letting the message dialog appear. I have the action listener in a separate class and the menu item in a separate class and I'm trying to get them to work together.
public class HangmanView {
Listener listener = new Listener();
public JMenuItem getMenuItem() {
JMenuItem menuItem = new JMenuItem("Developer", KeyEvent.VK_T);
menuItem.addActionListener(new Listener());
return menuItem;
}
public JMenuBar menuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("File");
menuBar.add(menu);
menu.add(getMenuItem());
return menuBar;
}
Another Class:
public class Listener {
JFrame dialogFrame = new JFrame();
public JFrame menuItemListener() {
HangmanView hangmanView = new HangmanView();
hangmanView.getMenuItem().addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {// right click key
JOptionPane.showMessageDialog(dialogFrame, "Developer: Joe"
, "Developer",
JOptionPane.INFORMATION_MESSAGE);
}// end actionPerformed method
});
return dialogFrame;
}
}
You seem to be suffering from a lot of confusion as to classes, interfaces, etc so it's actually hard to know where to begin!
First up your Listener class needs to implement ActionListener.
Then you need to add it inside your HangmanView class the same way you already are:
public class Listener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {// right click key
JOptionPane.showMessageDialog(dialogFrame, "Developer: Joe"
, "Developer",
JOptionPane.INFORMATION_MESSAGE);
}// end actionPerformed method
});
And that's it, you are done...

Need MouseOutEvent of MenuBar to detect click: GWT

I am a beginner using GWT. I have a menubar which I want to retain on the screen even if the mouse is not over it. However when the mouse is not over the menubar and clicked somewhere on the screen then I want the menubar to disappear. I tried using the MouseOutEvent but I need it to fire only when the mouse is clicked not just out. Any help would be appreciated.
this.menu.addDomHandler(menuHoverOutHandler, MouseOutEvent.getType());
MouseOutHandler menuHoverOutHandler = new MouseOutHandler() {
public void onMouseOut(MouseOutEvent event) {
Window.alert("I am outside the region");
}
};
Below is a fully working answer taken from my live app:
The way I solved the menu close on mouse out was to run a boolean variable "isMouseOut" in the top of the constructor to keep track, and then allocate the MouseListener in a more OO friendly way to keep track of the multiple MouseIn-MouseOut events as a user interacts with the menu. Which calls a separate menuClear method acting upon the state of the boolean "isMouseOut". The class implements MouseListener. This is how its done.
Create an ArrayList adding all the menu items to this array first. Like so:
Font menuFont = new Font("Arial", Font.PLAIN, 12);
JMenuBar menuBar = new JMenuBar();
getContentPane().add(menuBar, BorderLayout.NORTH);
// Array of MenuItems
ArrayList<JMenuItem> aMenuItms = new ArrayList<JMenuItem>();
JMenuItem mntmRefresh = new JMenuItem("Refresh");
JMenuItem mntmNew = new JMenuItem("New");
JMenuItem mntmNormal = new JMenuItem("Normal");
JMenuItem mntmMax = new JMenuItem("Max");
JMenuItem mntmStatus = new JMenuItem("Status");
JMenuItem mntmFeedback = new JMenuItem("Send Feedback");
JMenuItem mntmEtsyTWebsite = new JMenuItem("EtsyT website");
JMenuItem mntmAbout = new JMenuItem("About");
aMenuItms.add(mntmRefresh);
aMenuItms.add(mntmNew);
aMenuItms.add(mntmNormal);
aMenuItms.add(mntmMax);
aMenuItms.add(mntmStatus);
aMenuItms.add(mntmFeedback);
aMenuItms.add(mntmEtsyTWebsite);
aMenuItms.add(mntmAbout);
then iterate over the arrayList at this stage adding a MouseListener using the for() loop:
for (Component c : aMenuItms) {
if (c instanceof JMenuItem) {
c.addMouseListener(ml);
}
}
Now set JMenu parents for the MenuBar:
// Now set JMenu parents on MenuBar
final JMenu mnFile = new JMenu("File");
menuBar.add(mnFile).setFont(menuFont);
final JMenu mnView = new JMenu("View");
menuBar.add(mnView).setFont(menuFont);
final JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp).setFont(menuFont);
Then add the dropdown menuItems children to the JMenu parents:
// Now set menuItems as children of JMenu parents
mnFile.add(mntmRefresh).setFont(menuFont);
mnFile.add(mntmNew).setFont(menuFont);
mnView.add(mntmNormal).setFont(menuFont);
mnView.add(mntmMax).setFont(menuFont);
mnHelp.add(mntmStatus).setFont(menuFont);
mnHelp.add(mntmFeedback).setFont(menuFont);
mnHelp.add(mntmEtsyTWebsite).setFont(menuFont);
mnHelp.add(mntmAbout).setFont(menuFont);
Add the mouseListeners to the JMenu parents as a separate step:
for (Component c : menuBar.getComponents()) {
if (c instanceof JMenu) {
c.addMouseListener(ml);
}
}
Now that the child menuItem elements all have their own listeners that are separate to the parent JMenu elements and the MenuBar itself - It is important to identify the object type within the MouseListener() instantiation so that you get the menu auto opening on mouseover (in this example the 3x JMenu parents) BUT ALSO avoids child exception errors and allows clean identification of mouseOUT of the menu structure without trying to monitor where the mouse position is. The MouseListener is as follows:
MouseListener ml = new MouseListener() {
public void mouseClicked(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseExited(MouseEvent e) {
isMouseOut = true;
timerMenuClear();
}
public void mouseEntered(MouseEvent e) {
isMouseOut = false;
Object eSource = e.getSource();
if(eSource == mnHelp || eSource == mnView || eSource == mnFile){
((JMenu) eSource).doClick();
}
}
};
The above only simulates the mouse click into the JMenu 'parents' (3x in this example) as they are the triggers for the child menu dropdowns. The timerMenuClear() method calls on the MenuSelectionManager to empty whatever selectedpath point was live at the time of real mouseOUT:
public void timerMenuClear(){
ActionListener task = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(isMouseOut == true){
System.out.println("Timer");
MenuSelectionManager.defaultManager().clearSelectedPath();
}
}
};
//Delay timer half a second to ensure real mouseOUT
Timer timer = new Timer(1000, task);
timer.setInitialDelay(500);
timer.setRepeats(false);
timer.start();
}
It took me a little testing, monitoring what values I could access within the JVM during its development - but it Works a treat! even with nested menus :) I hope many find this full example very useful.
Use widget's blur handler. It detects when the widget lost focus.

How to make MouseClicked event work in java

I am pretty sure this is very easy and that I am only missing one line or two but I just cannot make this work despite searching for solutions over the internet. I am fairly new to java and my problem is in a desktop application.
I have a pretty simple desktop application with one text area, one menu bar with one menu and 3 menu item. I want to edit the text of the text area when I click on the Statistic menu item in a JFrame.
Here is the part of the code where I create the menu bar, menu and menu items (as well as their events):
//menu
mnuRevision.setText("Revision");
mnuitmStats.setText("Statistique");
mnuitmStats.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
mnumnuitmStatsMouseClicked(evt);
}
});
mnuRevision.add(mnuitmStats);
mnuitmOrthographe.setText("Grammaire et orthographe");
mnuitmOrthographe.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
mnuitmOrthographeMouseClicked(evt);
}
});
mnuRevision.add(mnuitmOrthographe);
mnuitmAnalyse.setActionCommand("Analyse");
mnuitmAnalyse.setText("Analyse");
mnuRevision.add(mnuitmAnalyse);
jMenuBar1.add(mnuRevision);
setJMenuBar(jMenuBar1);
Here is the Mousclicked function:
private void mnumnuitmStatsMouseClicked(java.awt.event.MouseEvent evt){
this.txtTexte.setText("asdf");
this.repaint();
}
What I want to do is when I click on mnuitemStats, the txtTexte will get the text "asdf" written in it. Somehow, this is not working. It looks like the program is not even getting into the function. I looked on some tutorials and they pretty much have the same code as me except for the objects names since most tutorials uses JButton instead of JMenuItem.
I can provide my whole code if it is needed, but I thought the rest would be irrelevant since it does not touch the menu bar or the textarea. I am using Eclipse Java EE IDE.
I usually write something like
mnuitemStats.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event)
{// your logic here;
}});
Assuming mnuitmStats is a JMenuItem, it should be. A little more code would be helpful but given that assumption you should use ActionListener not a MouseListener for this.
Something like:
class MenuActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
//do something
}
}
and
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
JMenuItem newMenuItem = new JMenuItem("New");
newMenuItem.addActionListener(new MenuActionListener());
fileMenu.add(newMenuItem);

How to execute button by clicking on another button java?

menuBar = new JMenuBar();
// File Menu
JMenu fileMenu = new JMenu("File");
menuBar.add(fileMenu);
// File->New
JMenuItem newMenuItem = new JMenuItem("New");
frame.setJMenuBar(menuBar);
newMenuItem.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
btnExample.setText("Clicked");
btnExample.doClick();
//---------->SOME HOW TO EXECUTE btnExample<---------//
}
});
fileMenu.add(newMenuItem);
final JButton btnExample = new JButton("SD");
frame.getContentPane().add(btnExample, "cell 4 0,growx,aligny top");
btnExample.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
spinnerForVar.setValue(4);//default value for spinner
spinnerForFunc.setValue(4);//default value for spinner
...
}
});
Hello! I hope someone can help me. Here it is the problem: I have Menu item "New" and have button btnExample. I want the following: When i click on "File->New" it executes btnExample. My code is able only to change the button title and show visual affect of clicking. But how can I actually execute it?
I have only one advice - don't do that. Don't bind GUI components in this way.
If you want two components to execute the same operation, simply pack this operation in a method and call the method from both components.
Also, use ActionListener - are you sure the user is going to press it using mouse and not keyboard? what if you add shortcuts to those buttons/components?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//My button to click on it
jButton1ActionPerformed(evt);//this is the call for the other button to execut it
}
You should not be using a MouseListener for this.
You should be using Actions. Then you can add the Action to both the JButton and the JMemuItem.
Read the section from the Swing tutorial on How to Use Actions.
Amazing, I found my solution in your codes!
btnExample.doClick();
This did the job for me

Categories