Java JMenu actionPerformed doesn't work - java

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

Related

JMenuBar buttons not responding [duplicate]

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.

Java - how do I check whether a JFrame is closed

When a user clicks the red 'X' button of a JFrame, how do I detect whether the JFrame is open or closed? I have a swing timer where the JFrame keeps updating it's label until the user closes down the JFrame.
int delay = 1000; //milliseconds
final Timer timer = new Timer(delay, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
tempLabel.setVisible(true);
String tmp = "test";
tempLabel.setText("Temperature : " + tmp);
// timer.stop();
}
});
timer.start();
You have to implement either the WindowStateListener or the WindowListener. If you use the WindowListener it could look like this:
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.Timer;
public class Foo implements WindowListener {
private Timer timer;
public static void main(String args[]){
initTimerComponent();
}
private void initTimerComponent() {
int delay = 1000; //milliseconds
timer = new Timer(delay, null);
timer.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
tempLabel.setVisible(true);
String tmp = "test";
tempLabel.setText("Temperature : " + tmp);
}
});
timer.start();
}
#Override
public void windowOpened(WindowEvent e) { }
#Override
public void windowClosing(WindowEvent e) {
timer.stop();
}
#Override
public void windowClosed(WindowEvent e) { }
#Override
public void windowIconified(WindowEvent e) { }
#Override
public void windowDeiconified(WindowEvent e) { }
#Override
public void windowActivated(WindowEvent e) { }
#Override
public void windowDeactivated(WindowEvent e) { }
}
You have to implement them all as WindowListener is an interface and the first concrete class implementing an interface is forced to implement all its abstract methods. But you actually need just one method.
Use this method
public void windowClosing(WindowEvent e) {
timer.stop();
}
to stop your timer as soon as the window is closing after the user clicked the red X.
Answer
addWindowListener(new WindowAdapter() {
//for closing
#Override
public void windowClosing(WindowEvent e) {
JOptionPane.showMessageDialog(null, "Closing");
}
//for closed
#Override
public void windowClosed(WindowEvent e) {
}
});

Java Swing GUI. Activating/Firing more buttons while keeping the mousebutton pressed

If I want to do an action, if a button is pressed I can use a ActionListener. But now if I want to activate more buttons by keeping the mousebutton pressed.
How can I implement this?
Thanks
Add a ChangeListener to the buttons ButtonModel, monitor for a change to the isPressed state.
The trick then is setting up some process which can then add the other components, in this simple example, I've used a Swing Timer, which will add roughly 40 new components a second while the button is pressed
public class TestPane extends JPanel {
private Timer timer = new Timer(25, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
add(new JButton("..."));
revalidate();
repaint();
}
});
public TestPane() {
JButton btn = new JButton("Help");
btn.getModel().addChangeListener(new ChangeListener() {
#Override
public void stateChanged(ChangeEvent e) {
ButtonModel model = (ButtonModel) e.getSource();
if (model.isPressed()) {
timer.start();
} else {
timer.stop();
}
}
});
add(btn);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
Thanks, this works if I press one Button. But if I press one Button and move the mouse with pressed mousebutton to another Button the secound button does nothing
Just so we're clear, I think this is a bad user experience, but that's me
public class Test {
public static void main(String[] args) {
new Test();
}
private boolean pressed = false;
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
public TestPane() {
add(makeButton("1"));
add(makeButton("2"));
}
protected JButton makeButton(String text) {
JButton btn = new JButton(text);
MouseAdapter ma = new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
pressed = true;
}
#Override
public void mouseReleased(MouseEvent e) {
pressed = false;
}
#Override
public void mouseEntered(MouseEvent e) {
if (pressed) {
JButton btn = (JButton) e.getComponent();
System.out.println("Entered " + btn.getText());
btn.doClick();
}
}
};
btn.addMouseListener(ma);
btn.addMouseMotionListener(ma);
return btn;
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
}
}
#npinti Now I can do an action for every button over which i hover with my mouse. But if I try to change the implementation, so that the action are only done, if the mouse is also clicked, the action only works if i press a button and over the same button again. `JButton b = new JButton();
if(a==1){
b.setBackground(Color.WHITE);
}else{
b.setBackground(Color.BLACK);
}
b.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent arg0 ) {
matrix.activate(x,y);
}
});
b.addMouseListener(new MouseListener() {
int pressed =0;
#Override
public void mouseReleased(MouseEvent e) {
pressed =0;
}
#Override
public void mousePressed(MouseEvent e) {
pressed =1;
}
#Override
public void mouseExited(MouseEvent e) {
}
#Override
public void mouseEntered(MouseEvent e) {
if (e.getComponent().equals(b) && pressed ==1){
b.setBackground(Color.BLACK);
}
}
public void mouseClicked(MouseEvent e) {
pressed =1;
}
});`
Catch mouseEntered on your buttons and if a global boolean pressed is true (set it to true when you press a mouse button and false on release), fire an action with JButton.doClick() which simulates a click event on the button.

KeyListener won't listen on JPanel

It's a very simple program, but for some reason when I debug it and set breakpoints at the keyPressed, keyReleased and keyTyped method, the program never stops there.
mainKeyListener = new KeyListener() {
public void keyPressed(KeyEvent e) {
System.out.println("KEY PRESSED");
repaint();
}
}
#Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
#Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
};
Here I add it to a JPanel, which is the exact size of the frame and the only object on it:
JPanel backgroundPanel = new JPanel();
backgroundPanel.setBounds(0,0, 400, 500);
backgroundPanel.addKeyListener(mainKeyListener);
backgroundPanel.setFocusable(true);
getContentPane().add(backgroundPanel);
Your problem is laying in focused element. I think that your panel lost the focus.
Note:
To fire keyboard events, a component must have the keyboard focus. It can be solved in many ways for your example you can use KeyboardFocusManager for example like this:
KeyboardFocusManager focusManager = KeyboardFocusManager.getCurrentKeyboardFocusManager();
focusManager.addKeyEventDispatcher(new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if(focusManager.getFocusOwner()!=backgroundPanel){
focusManager.redispatchEvent(backgroundPanel,e);
return true;}
else return false;
}
});
Also try to use Key Bindings http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html
Hi this should work for you.
public class Gui extends JFrame
{
private JPanel backgroundPanel = new JPanel();
public Gui() throws HeadlessException
{
this.setLayout(new GridLayout(1,1));
setPanelProps();
backgroundPanel.addKeyListener(createListener());
this.add(backgroundPanel);
this.setVisible(true);
this.setSize(new Dimension(400,500));
}
public void setPanelProps(){
backgroundPanel.setBounds(0, 0, 400, 500);
backgroundPanel.setSize(new Dimension(400,500));
backgroundPanel.setFocusable(true);
backgroundPanel.setBackground(new Color(50,60,70));
}
public KeyListener createListener(){
return new KeyListener() {
#Override
public void keyTyped(KeyEvent e)
{
System.out.println("KEY TYPED");
}
public void keyPressed(KeyEvent e) {
System.out.println("KEY PRESSED");
repaint();
}
#Override
public void keyReleased(KeyEvent e)
{
System.out.println("KEY RELEASED");
}
};
}
}
public class GuiRun
{
public static void main(String[] args)
{
Gui gui = new Gui();
}
}

Java: Cancel Button does not close the window for JFrame

I want the window to close when I press on Cancel button, but it's not working.
Code:
public class FirstClass{
private JFrame frame;
private JButton btnCancel;
public FirstClass() {
frame = new JFrame("GRIIS Data Transfer [Mobile to PC]");
frame.setBounds(200,200,900,450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
btnCancel = new JButton("Cancel");
btnCancel.setBounds(800, 5, 85, 25);
frame.add(btnCancel);
btnCancel.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
frame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
System.exit(0);
}
});
}
});
}//end of constructor
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
FirstClass window = new FirstClass();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
Please let me know in case of changes needed in the code.
btnCancel.addActionListener()
so my code will work and close the application when I press on Cancel button.
Dont use window listner it gives event at time of closing, try
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}});
No need to override WindowListener method,
public void actionPerformed(ActionEvent e) {
System.exit(0);
}

Categories