Access components of JFrame within MouseAdapter - java

what is the right way to access elements from a parent component when an adapter is used? Example:
In my JFrame is a Menu with an item "Connect". I handle the "pressed" event with a MouseAdapter:
mntmConnect.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent arg0) {
mainDialog.getY();
}
});
As you can see I want to access components or methods of the mainDialog where this Menu(item) belongs to. But in that MouseAdapter of course no "mainDialog" is known.
So here are my approaches:
1. Declare attributes that a needed as final
2. Create your own MouseAdapter that takes "mainDialog" as a variable in the ctor
Both of them seem circumstantial to me. What is the right way to do this?

What is the right way to do this?
All 3 of these approaches are right.
Declare attributes that are needed for an anonymous class as final.
Declare attributes that are needed for an anonymous class as class global.
Create a MouseAdapter class that takes "mainDialog" as a variable in the constructor.
I tend to use 2 for small MouseAdapter anonymous classes.
I tend to use 3 for larger MouseAdapter classes. I make these separate classes and put them in a controller package.

I handle the "pressed" event with a MouseAdapter
You should NOT be doing this. You should be adding and ActionListener (or Action) to the JMenuItem.
All compnents have a parent. So if you want to know the parent window of the menu item that was clicked you need to keep finding the parents component until you reach the window. Here is one way:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuItemFrame extends JFrame implements ActionListener
{
public MenuItemFrame()
{
JMenuBar menuBar = new JMenuBar();
setJMenuBar( menuBar );
JMenu menu = new JMenu( "File" );
menuBar.add( menu );
JMenuItem item1 = new JMenuItem("Item 1");
item1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0, false));
menu.add( item1 );
JMenu subMenu1 = new JMenu("SubMenu 1");
menu.add( subMenu1 );
JMenuItem subItem1 = new JMenuItem("SubItem 1");
subMenu1.add( subItem1 );
JMenu subMenu12 = new JMenu("SubMenu 12");
subMenu1.add( subMenu12 );
JMenuItem subItem12 = new JMenuItem("SubItem 12");
subMenu12.add( subItem12 );
item1.addActionListener( this );
subItem1.addActionListener( this );
subItem12.addActionListener( this );
}
public void actionPerformed(ActionEvent e)
{
JMenuItem mi = (JMenuItem)e.getSource();
mi.setText(mi.getText() + "0");
JMenu menu = getMenuBarMenu(mi);
JRootPane rootPane = SwingUtilities.getRootPane(menu);
JFrame frame = (JFrame)SwingUtilities.windowForComponent(menu);
System.out.println(frame);
}
public JMenu getMenuBarMenu(JMenuItem item)
{
JMenu menu = null;
while (menu == null)
{
JPopupMenu popup = (JPopupMenu)item.getParent();
item = (JMenuItem)popup.getInvoker();
if (! (item.getParent() instanceof JPopupMenu) )
menu = (JMenu)item;
}
return menu;
}
public static void main(String[] args)
{
JFrame frame = new MenuItemFrame();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.setSize(200, 200);
frame.setLocationRelativeTo( null );
frame.setVisible(true);
}
}

Related

How to use DefaultEditorKit in an AbstractAction

My notepad program that I'm writing uses AbstractActions for each item in the JMenuBar, and I want to keep it consistent that way throughout my code. And now I'm implementing Cut, Copy, Paste into the program but I'm unsure of how to do that with Action.
import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
public class Home {
static Action Cut = new AbstractAction("Cut-Action") {
public void actionPerformed(ActionEvent e) {
// Where I want to use cut
new DefaultEditorKit.CutAction();
}
};
static public JMenuBar createMenuBar() {
JMenuBar menuBar = new JMenuBar();
JMenu menu = new JMenu("Edit");
menu.add(Cut); // Adds the cut action
// adds the non-action method
JMenuItem item = new JMenuItem(new DefaultEditorKit.CutAction());
item.setText("Cut-NonAction");
menu.add(item);
menuBar.add(menu);
return menuBar;
}
public static void main(String[] args) {
JFrame frame = new JFrame("Home");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JMenuBar menuBar = createMenuBar();
frame.add(menuBar, BorderLayout.NORTH);
JTextPane txt = new JTextPane();
JScrollPane s = new JScrollPane(txt);
frame.add(s, BorderLayout.CENTER);
frame.setSize(400, 300);
frame.setVisible(true);
}
}
How would I be able to use the cut action in my abstract action??
I figured it out with a little bit of trial and error.
I changed this code:
public void actionPerformed(ActionEvent e) {
new DefaultEditorKit().CutAction();
}
to:
public void actionPerformed(ActionEvent e) {
Action cut = new DefaultEditorKit.CutAction();
cut.actionPerformed(e);
}
How would I be able to use the cut action in my abstract action??
Why are you trying to do this? The is not the way to use the Actions from the editor kit.
This is the proper way to use the actions:
JMenuItem item = new JMenuItem(new DefaultEditorKit.CutAction());
Or if you happen to need the CutAction on a menu and on a toolbar you would use code like:
Action cut = new DefaultEditorKit.CutAction();
cut.putValue(Action.NAME, "Cut");
JMenuItem cutMenuItem = new JMenuItem( cut );
JButton cutButton = new JButton( cut );
Now the same Action is shared which means you can enable/disable the Action and both components will be affected. Read the section from the Swing tutorial on How to Use Actions for more information and examples.

Where do I put this statement 'setJMenuBar(menuBar);'?

Main Class:
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Main extends JFrame {
public static void main(String[] args) {
JFrame frame = new JFrame("Checking Account Actions");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
CheckingAccountActions panel = new CheckingAccountActions();
MyWindowAdapter winAdapter = new MyWindowAdapter(panel);
frame.addWindowListener(winAdapter);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
} // Main()
class MyWindowAdapter extends WindowAdapter {
private CheckingAccountActions saved;
public MyWindowAdapter(CheckingAccountActions saved) {
this.saved = saved;
}
// in your window closing method
// check the state of checkActions first before doing anything
public void windowClosing(WindowEvent e) {
// note -- don't check for saved in a static way
// use a method on the instance.
if(!saved.saved) {
String message = "The data in the application is not saved.\n"
+ "Would you like to save it before exiting the
+ application?";
int confirm = JOptionPane.showConfirmDialog (null, message);
if (confirm == JOptionPane.YES_OPTION)
CheckingAccountActions.chooseFile(2);
}
JFrame frame = (JFrame)e.getSource();
frame.setVisible(false);
// Main.frame.setVisible(false);
System.exit(0);
}
} // MyWindowAdapter()
This class, as you see, extends JPanel and this is where my Menu items are initialized, but do I use Main class for this statement 'setJMenuBar(menuBar);', since it gives an error in CheckingAccountActions because JFrame is in MAIN.
CheckingAccountActions class:
public class CheckingAccountActions extends JPanel {
// Panel
private JLabel message;
// Menu
private JMenuBar menuBar;
private JMenu File;
private JMenuItem Read, Write;
private JMenu Account;
private JMenuItem NewAccount, ListAccounts, ListChecks, ListDeposits, FindAccount;
private JMenu Transactions;
private JMenuItem AddTransactions;
// code...
//
//
// code...
public CheckingAccountActions() {
//************************** PANEL *****************************************
// JLabel
message = new JLabel("Please choose one of the items: ");
message.setFont(new Font("Helvetica", Font.BOLD, 15));
CheckingAccountActionsListener listener = new CheckingAccountActionsListener();
//************************** MENU ******************************************
// Menu
File = new JMenu("File");
// MenuItem
Read = new JMenuItem("Read from file");
Write = new JMenuItem("Write to file");
// ActionListener
Read.addActionListener(listener);
Write.addActionListener(listener);
// Add Buttons to Menu
File.add(Read);
File.add(Write);
// Menu
Account = new JMenu("Account");
// MenuItem
NewAccount = new JMenuItem("Add new account");
ListAccounts = new JMenuItem("List accounts transaction");
ListChecks = new JMenuItem("List all checks");
ListDeposits = new JMenuItem("List all deposits");
FindAccount = new JMenuItem("Find an account");
// ActionListener
NewAccount.addActionListener(listener);
ListAccounts.addActionListener(listener);
ListChecks.addActionListener(listener);
ListDeposits.addActionListener(listener);
FindAccount.addActionListener(listener);
// Add Buttons to Menu
Account.add(NewAccount);
Account.add(ListAccounts);
Account.add(ListChecks);
Account.add(ListDeposits);
Account.add(FindAccount);
// Menu
Transactions = new JMenu("Transactions");
// MenuItem
AddTransactions = new JMenuItem("Add Transactions");
// ActionListener
AddTransactions.addActionListener(listener);
// Add Buttons to Menu
Transactions.add(AddTransactions);
// MenuBar
menuBar = new JMenuBar();
menuBar.add(File);
menuBar.add(Account);
menuBar.add(Transactions);
setBackground(Color.white);
setPreferredSize(new Dimension(240, 250));
setJMenuBar(menuBar);
}
private class CheckingAccountActionsListener implements ActionListener {
// code...
}
Edit: what I am confused about is how to add my MenuBar to the Frame while the Frame is in another class?
FINAL EDIT: I got it working. I just moved all my JFrame components to CheckingAccountActions class.
Take a look at the section from the Swing tutorial on How to Use Menus. The MenuDemo example will show you one way to structure your program.
It also shows you the proper way to create your GUI on the Event Dispatch Thread.
setJMenuBar(menubar) is not what you actually looking for. If you want to set the menubar to your frame, just add the menu bar to the frame with the method add(menuBar).

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.

Can't Add JMenuItem to JMenu in JPopupMenu

I've got a new UI I'm working on implementing in Java and I'm having trouble implementing a JPopupMenu containing a JMenu (as well as several JMenuItems), which itself contains several JMenuItems. The JPopupMenu appears where I click the RMB, and it looks good, but the "Connect" JMenu doesn't seem to have any children when I mouse-over, despite my best efforts to .add() them.
Having looked at several examples online, I haven't seen any that specifically implement a listener for mouseEntered() to roll out the sub-items. I'm of a mind that I'm messing something up in my menu initialization method.
I've attached the pertinent code for your perusal.
//Elsewhere...
private JPopupMenu _clickMenu;
//End Elsehwere...
private void initializeMenu()
{
_clickMenu = new JPopupMenu();
_clickMenu.setVisible(false);
_clickMenu.add(generateConnectionMenu());
JMenuItem menuItem;
menuItem = new JMenuItem("Configure");
addMenuItemListeners(menuItem);
_clickMenu.add(menuItem);
menuItem = new JMenuItem("Status");
addMenuItemListeners(menuItem);
_clickMenu.add(menuItem);
}
private JMenu generateConnectionMenu()
{
JMenu menu = new JMenu("Connect");
List<Port> portList = _database.getAllPortsInCard(_cardId);
for(int i = 0; i < portList.size(); i++)
{
menu.add(new JMenuItem(portList.get(i).getName()));
}
return menu;
}
The code is certainly not the prettiest, but go easy on me as it's been altered too many times today as time permitted while I tried to figure out why this wasn't working. I'm thinking it may be a question of scope, but I've tried a few different code configurations to no avail. Feel free to ask any followup questions or smack me for an obvious oversight (it's happened before...). Thanks all!
Edit:
Chalk this one up to a lack of experience with Java and Swing... I was manually positioning and making the JPopupMenu visible instead of using the JComponent.setComponentPopupMenu(menu) method. After doing this for the card module in the above image (itself a JButton), the submenu displays correctly. A different, functional version of the initialization code is included below.
private void initializeMenu()
{
_cardMenu = new JPopupMenu();
JMenu menu = new JMenu("Connect");
JMenuItem menuItem;
menuItem = new JMenuItem("1");
menu.add(menuItem);
menuItem = new JMenuItem("2");
menu.add(menuItem);
_cardMenu.add(menu);
_cardMenu.add(new JMenuItem("Configure"));
_cardMenu.add(new JMenuItem("Status"));
_mainButton.setComponentPopupMenu(_cardMenu); //Important, apparently!
}
So, lesson learned. Thanks for the help guys!
This is common Bug or Swing property that in one moment can be visible only one Lightweight popup window, same issue is e.g. with popup from JComboBox added into JPopupMenu,
change Lightweight property to the Heavyweight
better would be
use un_decorated JDialog or JOptionPane with JComponents
EDIT #trashgod
everything works as I excepted, all JMenus, JMenuItems are visible and repeatly fired correct evets
code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ContextMenu implements ActionListener, MenuListener, MenuKeyListener {
private JTextArea textArea = new JTextArea();
public ContextMenu() {
final JPopupMenu contextMenu = new JPopupMenu("Edit");
JMenu menu = new JMenu("Sub Menu");
menu.add(makeMenuItem("Sub Menu Save"));
menu.add(makeMenuItem("Sub Menu Save As"));
menu.add(makeMenuItem("Sub Menu Close"));
menu.addMenuListener(this);
JMenu menu1 = new JMenu("Sub Menu");
menu1.add(makeMenuItem("Deepest Sub Menu Save"));
menu1.add(makeMenuItem("Deepest Sub Menu Save As"));
menu1.add(makeMenuItem("Deepest Sub Menu Close"));
menu.add(menu1);
menu1.addMenuListener(this);
contextMenu.add(menu);
contextMenu.add(makeMenuItem("Plain Save"));
contextMenu.add(makeMenuItem("Plain Save As"));
contextMenu.add(makeMenuItem("Plain Close"));
contextMenu.addMenuKeyListener(this);
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
frame.add(panel);
panel.setComponentPopupMenu(contextMenu);
textArea.setInheritsPopupMenu(true);
panel.add(BorderLayout.CENTER, textArea);
JTextField textField = new JTextField();
textField.setInheritsPopupMenu(true);
panel.add(BorderLayout.SOUTH, textField);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 200);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
textArea.append(e.getActionCommand() + "\n");
}
private JMenuItem makeMenuItem(String label) {
JMenuItem item = new JMenuItem(label);
item.addActionListener(this);
return item;
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ContextMenu contextMenu = new ContextMenu();
}
});
}
public void menuSelected(MenuEvent e) {
textArea.append("menuSelected" + "\n");
}
public void menuDeselected(MenuEvent e) {
textArea.append("menuDeselected" + "\n");
}
public void menuCanceled(MenuEvent e) {
textArea.append("menuCanceled" + "\n");
}
public void menuKeyTyped(MenuKeyEvent e) {
textArea.append("menuKeyTyped" + "\n");
}
public void menuKeyPressed(MenuKeyEvent e) {
textArea.append("menuKeyPressed" + "\n");
}
public void menuKeyReleased(MenuKeyEvent e) {
textArea.append("menuKeyReleased" + "\n");
}
}
I don't see an obvious problem in the code shown, although #mKorbel's point may apply. For reference, this ControlPanel adds a subMenu with several items.

Add functionality to a menu button in java

I am new to Java and I was wondering how to add functionality to menu item?
What I would like it to do, is to set two values to 0.
This is the code I have currently:
JMenuItem clear = new JMenuItem("Clear");
Options.add(clear);
This example is from the book "Java
Foundation Classes in a Nutshell".
Written by David Flanagan. Copyright
(c) 1999 by O'Reilly & Associates.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MenuDemo {
public static void main(String[] args) {
// Create a window for this demo
JFrame frame = new JFrame("Menu Demo");
JPanel panel = new JPanel();
frame.getContentPane().add(panel, "Center");
// Create an action listener for the menu items we will create
// The MenuItemActionListener class is defined below
ActionListener listener = new MenuItemActionListener(panel);
// Create some menu panes, and fill them with menu items
// The menuItem() method is important. It is defined below.
JMenu file = new JMenu("File");
file.setMnemonic('F');
file.add(menuItem("New", listener, "new", 'N', KeyEvent.VK_N));
file.add(menuItem("Open...", listener, "open", 'O', KeyEvent.VK_O));
file.add(menuItem("Save", listener, "save", 'S', KeyEvent.VK_S));
file.add(menuItem("Save As...", listener, "saveas", 'A', KeyEvent.VK_A));
JMenu edit = new JMenu("Edit");
edit.setMnemonic('E');
edit.add(menuItem("Cut", listener, "cut", 0, KeyEvent.VK_X));
edit.add(menuItem("Copy", listener, "copy", 'C', KeyEvent.VK_C));
edit.add(menuItem("Paste", listener, "paste", 0, KeyEvent.VK_V));
// Create a menubar and add these panes to it.
JMenuBar menubar = new JMenuBar();
menubar.add(file);
menubar.add(edit);
// Add menubar to the main window. Note special method to add menubars
frame.setJMenuBar(menubar);
// Now create a popup menu and add the some stuff to it
final JPopupMenu popup = new JPopupMenu();
popup.add(menuItem("Open...", listener, "open", 0, 0));
popup.addSeparator(); // Add a separator between items
JMenu colors = new JMenu("Colors"); // Create a submenu
popup.add(colors); // and add it to the popup menu
// Now fill the submenu with mutually-exclusive radio buttons
ButtonGroup colorgroup = new ButtonGroup();
colors.add(radioItem("Red", listener, "color(red)", colorgroup));
colors.add(radioItem("Green", listener, "color(green)", colorgroup));
colors.add(radioItem("Blue", listener, "color(blue)", colorgroup));
// Arrange to display the popup menu when the user clicks in the window
panel.addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent e) {
// Check whether this is the right type of event to pop up a popup
// menu on this platform. Usually checks for right button down.
if (e.isPopupTrigger())
popup.show((Component)e.getSource(), e.getX(), e.getY());
}
});
// Finally, make our main window appear
frame.setSize(450, 300);
frame.setVisible(true);
}
// A convenience method for creating menu items.
public static JMenuItem menuItem(String label,
ActionListener listener, String command,
int mnemonic, int acceleratorKey) {
JMenuItem item = new JMenuItem(label);
item.addActionListener(listener);
item.setActionCommand(command);
if (mnemonic != 0) item.setMnemonic((char) mnemonic);
if (acceleratorKey != 0)
item.setAccelerator(KeyStroke.getKeyStroke(acceleratorKey,
java.awt.Event.CTRL_MASK));
return item;
}
// A convenience method for creating radio button menu items.
public static JMenuItem radioItem(String label, ActionListener listener,
String command, ButtonGroup mutExGroup) {
JMenuItem item = new JRadioButtonMenuItem(label);
item.addActionListener(listener);
item.setActionCommand(command);
mutExGroup.add(item);
return item;
}
// A event listener class used with the menu items created above.
// For this demo, it just displays a dialog box when an item is selected.
public static class MenuItemActionListener implements ActionListener {
Component parent;
public MenuItemActionListener(Component parent) { this.parent = parent; }
public void actionPerformed(ActionEvent e) {
JMenuItem item = (JMenuItem) e.getSource();
String cmd = item.getActionCommand();
JOptionPane.showMessageDialog(parent, cmd + " was selected.");
}
}
}
Hope it help you get started
You will need to add an ActionListener. This is an interface which must implement a method called actionPerformed.
E.g
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
// Clear two values.
}
});`
This will add an anonymous ActionListener that is invoked once the JMenuItem is clicked.
Hope that helps.

Categories