JMenuBar buttons not responding [duplicate] - java

I was wondering if can you test to see if a JMenu (not JMenuItem) has been clicked. I tried adding an ActionListener to it but it doesn't seem to recognize it. I just need it to preform an action when the JMenu button is pressed so that I can change the JMenuItems for that menu befor it opens. All work arrounds to get this result are welcome too!
Thanks

for JMenu use MenuListener
code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class ActionExample {
public ActionExample() {
JMenu menu = new JMenu("Menu");
menu.setMnemonic(KeyEvent.VK_M);
menu.addMenuListener(new SampleMenuListener());
JMenu menu1 = new JMenu("Tool");
menu1.setMnemonic(KeyEvent.VK_T);
menu1.addMenuListener(new SampleMenuListener());
JFrame f = new JFrame("ActionExample");
JMenuBar mb = new JMenuBar();
mb.add(menu);
mb.add(menu1);
f.setJMenuBar(mb);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
ActionExample actionExample = new ActionExample();
}
});
}
}
class SampleMenuListener implements MenuListener {
#Override
public void menuSelected(MenuEvent e) {
System.out.println("menuSelected");
}
#Override
public void menuDeselected(MenuEvent e) {
System.out.println("menuDeselected");
}
#Override
public void menuCanceled(MenuEvent e) {
System.out.println("menuCanceled");
}
}
for JMenuItem use only ButtonModel

I think it's possible to use a MouseListener to fire actions in JMenu without JMenuItem.
JMenu myMenu = new JMenu("My menu");
myMenu.addMouseListener(new MouseListener() {
#Override
public void mouseClicked(MouseEvent e) {
// action here
}
#Override
public void mousePressed(MouseEvent e) {
}
#Override
public void mouseReleased(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
}
#Override
public void mouseExited(MouseEvent e) {
}
});
menuBar.add(myMenu);

With an instance of JMenu you can't add an ActionListener, only with JMenuItem you can do it.

Related

How to Change Default Inputs for JComboBox and JButton

How do I make the Enter key trigger a JComboBox or JButton in a GUI rather than having to hit the Space key? I have an assortment of text fields and check boxes with buttons and combo boxes in between. I'd like to avoid having to switch between hitting space and enter and rather only have to hit enter for all components.
package koning.personal.dungeonsanddragons;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class test {
JFrame window = new JFrame("testGUI");
JPanel windowPanel = new JPanel();
public static JLabel labelSize;
public static JComboBox<String> comboSize;
public static JLabel labelButton;
public static JButton buttonButton;
public test () {
super();
labelSize = new JLabel("Monster Size:");
String[] sizeChoices = { "None", "Tiny", "Small", "Medium", "Large", "Huge", "Colossal"};
comboSize = new JComboBox<String>(sizeChoices);
comboSize.setToolTipText("The creature's size.");
labelButton = new JLabel("Button:");
buttonButton = new JButton();
windowPanel.setLayout(new FlowLayout());
windowPanel.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);
windowPanel.add(labelSize);
windowPanel.add(comboSize);
windowPanel.add(labelButton);
windowPanel.add(buttonButton);
windowPanel.setVisible(true);
window.setSize(500, 500);
window.setLayout(new FlowLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setVisible(true);
window.add(windowPanel);
comboSize.addActionListener(handler);
buttonButton.addActionListener(handler);
}
ActionHandler handler = new ActionHandler();
public class ActionHandler implements ActionListener {
public void actionPerformed(ActionEvent eventFocus){
if (eventFocus.getSource() == comboSize){
buttonButton.requestFocusInWindow();
}
if (eventFocus.getSource() == buttonButton){
comboSize.requestFocusInWindow();
}
}
}
#SuppressWarnings("unused")
public static void main(String[] args) {
test GUITest = new test();
}
}
You can add a KeyListener and execute doClick
JButton btn = new JButton();
btn.addKeyListener(new KeyListener() {
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER)
btn.doClick();
}
#Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
#Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub
}
});
If the goal is to have something happen when the enter button is pressed (pressed once and something happens with all the components) then you can add a KeyListener to the JFrame:
JFrame frame = new JFrame("Examplpe");
//here you create and add the components to the frame
and then you can add a KeyListener:
frame.addKeyListener(new KeyListener(
#Override
public void keyTyped(KeyEvent e) {
if(e.getKeyCode == KeyEvent.VK_ENTER){//this is the if block I'm refering to in the following explanation
//do something with all the components
}
}
#Override
public void keyReleased(KeyEvent e) {}
#Override
public void keyPressed(KeyEvent e) {}
}
and then when you press Enter, the code inside the if block will be executed.
Hope this helps :)

ActionListener is only counting left mouse click

I learned this code from some tutorial but it only counts left mouse clicks. I try with MouseListener but it kept counting while the timer came to 0. And with ActionListener it isn't counting the right mouse clicks. Any suggestions? Maybe its a foolish question but I'm new here.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class game extends JFrame
{
private static final int SwingConstants=0;
Timer timer;
int timercounter;
int clickcounter;
JLabel directions,entertime,clicklabel,timeleft,label;
JButton startbutton,clickbutton;
JTextField tf;
JMenuBar menubar;
JMenu file,help;
JMenuItem reset,exit,mhelp;
JFrame frame=new JFrame();
public game()
{
Container pane=this.getContentPane();
pane.setLayout(new GridLayout(3,1,2,2));
menubar=new JMenuBar();
setJMenuBar(menubar);
file=new JMenu("File");
menubar.add(file);
help=new JMenu("Help");
menubar.add(help);
reset=new JMenuItem("Reset");
file.add(reset);
exit=new JMenuItem("Quit");
file.add(exit);
mhelp=new JMenuItem("More Help!!");
help.add(mhelp);
ResetClass rc=new ResetClass();
reset.addActionListener(rc);
ExitClass ec=new ExitClass();
exit.addActionListener(ec);
MhelpClass mc=new MhelpClass();
mhelp.addActionListener(mc);
JPanel top=new JPanel();
top.setLayout(new GridLayout(1,1));
directions=new JLabel("Enter time & press <Click Here> REPEATEDLY!!");
top.add(directions);
pane.add(top);
JPanel middle=new JPanel();
middle.setLayout(new GridLayout(1,3));
entertime=new JLabel("Enter Time (sec):");
middle.add(entertime);
tf=new JTextField();
middle.add(tf);
startbutton=new JButton("Click Here");
middle.add(startbutton);
pane.add(middle);
JPanel bottom=new JPanel();
bottom.setLayout(new GridLayout(1,3));
clickbutton=new JButton("Click Here!");
clickbutton.setEnabled(false);
bottom.add(clickbutton);
clicklabel=new JLabel("Clicks: 0");
bottom.add(clicklabel);
timeleft=new JLabel("Time left: ?");
bottom.add(timeleft);
pane.add(bottom);
StartButtonClass sbc=new StartButtonClass();
startbutton.addActionListener(sbc);
ClickButtonClass cbc=new ClickButtonClass();
clickbutton.addActionListener(cbc);
}
public class StartButtonClass implements ActionListener
{
#Override
public void actionPerformed(ActionEvent sbc)
{
try
{
int timeCount=(int)(Double.parseDouble(tf.getText()));
if(timeCount<=0)
{
tf.setText("Positive number!");
//startbutton.setEnabled(false);
}
else
{
timeleft.setText("Time left: "+timeCount);
TimeClass tc=new TimeClass(timeCount);
timer=new Timer(1000,tc);
timer.start();
startbutton.setEnabled(false);
clickbutton.setEnabled(true);
}
}
catch(NumberFormatException ex)
{
tf.setText("Number only!");
}
}
}
public class ClickButtonClass implements MouseListener
{
public void mouseReleased(MouseEvent cbc)
{
clickcounter++;
clicklabel.setText("Clicks: "+clickcounter);
}
#Override
public void mouseClicked(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mouseEntered(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mouseExited(MouseEvent e)
{
// TODO Auto-generated method stub
}
#Override
public void mousePressed(MouseEvent e)
{
// TODO Auto-generated method stub
}
}
public class TimeClass implements ActionListener
{
int timerCounter;
public TimeClass(int timerCounter)
{
this.timerCounter=timerCounter;
}
public void actionPerformed(ActionEvent tc)
{
timerCounter--;
if(timerCounter>=1)
{
timeleft.setText("Time left: "+timerCounter);
}
else
{
timer.stop();
timeleft.setText("Done!");
clickbutton.setEnabled(false);
Toolkit.getDefaultToolkit().beep();
}
}
}
public class ResetClass implements ActionListener
{
public void actionPerformed(ActionEvent rc)
{
clickbutton.setEnabled(false);
startbutton.setEnabled(true);
clickcounter=0;
clicklabel.setText("Clicks: 0");
tf.setText("");
timeleft.setText("Time left: ?");
}
}
public class ExitClass implements ActionListener
{
public void actionPerformed(ActionEvent ec)
{
System.exit(0);
}
}
public class MhelpClass implements ActionListener
{
public void actionPerformed(ActionEvent mc)
{
JOptionPane.showMessageDialog(null, "Read the Readme file carefully!!", "Help!!", JOptionPane.PLAIN_MESSAGE);
}
}
}
Use this it will let you see right mouse clicks
class MyMouseListener implements MouseListener{
#Override
public void mouseReleased(MouseEvent arg0) {
if(SwingUtilities.isRightMouseButton(arg0)&&clickButton.isEnabled()){
//my code
}
}

Java JMenu actionPerformed doesn't work

So, I've implemented anonymous action listener to JMenu component, so I'm wonder is it possible for JMenu to do some action with out JMenuItems in it, just JMenu, for example... Exit?
#Override
public void menuBarItemExit(JMenuBar menubar) {
exitMenuItem = new JMenu("Exit");
exitMenuItem.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
menubar.add(exitMenuItem);
}
Use a MenuListener instead of an ActionListener:
exitMenuItem.addMenuListener(new MenuListener() {
#Override
public void menuSelected(MenuEvent e) {
System.exit(0);
}
#Override
public void menuDeselected(MenuEvent e) {
}
#Override
public void menuCanceled(MenuEvent e) {
}
});
From Oracle: JMenu ignores ActionEvent

JTextField is not editable in a JPopupMenu

When I add a JtextField in a JPopupMenu, I can't edit the text when the popup is displayed. Anyone know why?
Here's a code example:
public static void main(String[] args) {
JFrame frame = new JFrame();
JPopupMenu popup = new JPopupMenu();
JTextField field = new JTextField("My text");
popup.insert(field, 0);
popup.setVisible(true);
}
Seems to work alright for me:
Check out this example (right click anywhere on the content pane to make the popup visible:
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPopupMenu;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
public class Main {
protected void initUI() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPopupMenu popup = new JPopupMenu();
final JTextField field = new JTextField(20);
field.setText("My text");
popup.insert(field, 0);
popup.addPopupMenuListener(new PopupMenuListener() {
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
field.requestFocusInWindow();
field.selectAll();
}
});
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
}
#Override
public void popupMenuCanceled(PopupMenuEvent e) {
}
});
((JComponent) frame.getContentPane()).setComponentPopupMenu(popup);
frame.setSize(300, 300);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new Main().initUI();
}
});
}
}
to avoiding any speculations
I can't edit the text when the popup is displayed. Anyone know why?
JPopup nested JPopupMenu must has a parent, my code example (reason why is there hardcodes frame.setLocation(150, 100);)
in this form works correctly, JPopup accepting JFrames coordinates
change this code inside Swing Action
from
//popupMenu.setVisible(true);
popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
to
popupMenu.setVisible(true);
//popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
then PopupMenuListener firing and events, but JMenuItems aren't repainted too
from code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class PopupSample {
private JPopupMenu popupMenu = new JPopupMenu();
private javax.swing.Timer timer = null;
private JFrame frame = new JFrame("Popup Example");
public PopupSample() {
ActionListener actionListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
System.out.println("Selected: "
+ actionEvent.getActionCommand());
}
};
PopupMenuListener popupMenuListener = new PopupMenuListener() {
#Override
public void popupMenuCanceled(PopupMenuEvent popupMenuEvent) {
System.out.println("Canceled");
}
#Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Invisible");
}
#Override
public void popupMenuWillBecomeVisible(PopupMenuEvent popupMenuEvent) {
System.out.println("Becoming Visible");
}
};
popupMenu.addPopupMenuListener(popupMenuListener);
JSeparator jSeparator = new JSeparator(JSeparator.VERTICAL);
jSeparator.setPreferredSize(new Dimension(2, 100));
jSeparator.setBackground(Color.red);
popupMenu.add(jSeparator);
JMenuItem cutMenuItem = new JMenuItem("Cut");
cutMenuItem.addActionListener(actionListener);
popupMenu.add(cutMenuItem);
cutMenuItem.setBorder(null);
JMenuItem copyMenuItem = new JMenuItem("Copy");
copyMenuItem.addActionListener(actionListener);
popupMenu.add(copyMenuItem);
JMenuItem pasteMenuItem = new JMenuItem("Paste");
pasteMenuItem.addActionListener(actionListener);
pasteMenuItem.setEnabled(false);
popupMenu.add(pasteMenuItem);
popupMenu.addSeparator();
JMenuItem findMenuItem = new JMenuItem("Find");
findMenuItem.addActionListener(actionListener);
popupMenu.add(findMenuItem);
JTextField text = new JTextField("text");
popupMenu.add(text);
MouseListener mouseListener = new JPopupMenuShower(popupMenu);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.addMouseListener(mouseListener);
frame.setLocation(150, 100);
frame.setSize(350, 250);
frame.setVisible(true);
start();
}
private void start() {
timer = new javax.swing.Timer(1000, updateCol());
timer.start();
}
public Action updateCol() {
return new AbstractAction("text load action") {
private static final long serialVersionUID = 1L;
#Override
public void actionPerformed(ActionEvent e) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
//popupMenu.setVisible(true);
popupMenu.show(frame, (frame.getHeight() / 4), (frame.getWidth() / 4));
}
});
}
};
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
PopupSample popupSample = new PopupSample();
}
});
}
static class JPopupMenuShower extends MouseAdapter {
private JPopupMenu popup;
public JPopupMenuShower(JPopupMenu popup) {
this.popup = popup;
}
private void showIfPopupTrigger(MouseEvent mouseEvent) {
if (popup.isPopupTrigger(mouseEvent)) {
popup.show(mouseEvent.getComponent(), mouseEvent.getX(),
mouseEvent.getY());
}
}
#Override
public void mousePressed(MouseEvent mouseEvent) {
showIfPopupTrigger(mouseEvent);
}
#Override
public void mouseReleased(MouseEvent mouseEvent) {
showIfPopupTrigger(mouseEvent);
}
}
}

getting right click location from popmenu action event

I have a java program that opens a popup menu when right clicked in a JPanel. When any of the popup menu items are clicked, I want to print the location of the right click that triggered the popupmenu in the terminal. How do I do this? How do I get the location of where the right click happened from within popup action events?
How does the code change if the popup menu is in a JComponent?
Here is the program.
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;
public class MenuTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MenuFrame frame = new MenuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class MenuFrame extends JFrame
{
public MenuFrame()
{
setTitle("MenuTest");
setSize(300, 200);
Action cutAction = new TestAction("Cut");
Action copyAction = new TestAction("Copy");
Action pasteAction = new TestAction("Paste");
JPopupMenu popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);
JPanel panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);
panel.addMouseListener(new MouseAdapter() {});
}
class TestAction extends AbstractAction
{
public TestAction(String name)
{
super(name);
}
public void actionPerformed(ActionEvent event)
{
System.out.println("Right click happened at ?"); // How do I get right click location?
}
}
}
Add a mouse listener to pressed events, (clicked events get captured by popup):
panel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
clickLocation.setSize(e.getX(), e.getY());
}
});
Action cutAction = new TestAction("Cut", clickLocation);
Action copyAction = new TestAction("Copy", clickLocation);
Action pasteAction = new TestAction("Paste", clickLocation);
Print out the dimension:
private Dimension clickLocation;
public TestAction(String name, Dimension clickLocation) {
super(name);
this.clickLocation = clickLocation;
}
public void actionPerformed(ActionEvent event) {
System.out.println("Right click happened at " + clickLocation);
}
you were on the right track. i personally prefer to show it manually in the MouseAdapter so i can add methods on other mouseevents. for this you probably need to remove the panel.setComponentPopupMenu(popup);
panel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
if (arg0.getButton() == MouseEvent.BUTTON3) { //Button3 is rightclick
popup.show(panel, arg0.getX(), arg0.getY());
}
}
});
Here is the code that I was looking for. Thank you Schippi and Garret for your help.
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;
import java.awt.geom.*;
public class MenuTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
MenuFrame frame = new MenuFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class MenuFrame extends JFrame
{
public MenuFrame()
{
setTitle("MenuTest");
setSize(300, 200);
Action cutAction = new TestAction("Cut");
Action copyAction = new TestAction("Copy");
Action pasteAction = new TestAction("Paste");
JPopupMenu popup = new JPopupMenu();
popup.add(cutAction);
popup.add(copyAction);
popup.add(pasteAction);
JPanel panel = new JPanel();
panel.setComponentPopupMenu(popup);
add(panel);
panel.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
clickLocation= e.getPoint();
}
});
}
class TestAction extends AbstractAction
{
public TestAction(String name)
{
super(name);
}
public void actionPerformed(ActionEvent event)
{
System.out.println("Right click happened at (" + clickLocation.getX()+"," + clickLocation.getY()+ ")");
}
}
private Point2D clickLocation;
}
Or if you don't want to get it from the event.
Point mousepospoint=null;
if((mousepospoint=componentname.getMousePosition()) != null){
//mouseposArray[0]=mousepospoint.x;
//mouseposArray[1]=mousepospoint.y;
mousepoints(mousepospoint.x,mousepospoint.y);
}//enif
int[] mouseposArray={0,0};
// requires a function to return it if mouseposArray[] is global
protected int[] mousepoints(int xpo,int ypo){
mouseposArray=new int[2];
mouseposArray[0]=xpo;
mouseposArray[1]=ypo;
return mouseposArray;
}//enmeth

Categories