I'm creating an application with a menu of some sort and I have a problem with my code.
I have 2 classes: the first class is the menu class. This class extends JPanel, the menu has a couple of buttons, each has an ActionListener. The second class is the main class, which extends JFrame.
I'm creating an instance of the menu class inside the main class. I added a mouseListener to the JFrame and tried to print the event every time the mouse was clicked. Unfortunately when I click on one of the buttons in the menu the ActionListener inside the menu works, but the mouseEvent on the JFrame doesn't (I tried using mouseListener in the menu as well but it didn't work).
My goal is to get the button (source) that was pressed in the menu from the JFrame class. Thanks for your help!
Example:
Class menu extends JPanel implements ActionListener
{
JButton b;
public menu()
{
b = new JButton() ;
b.setBounds(100,100,100,100);
b.addActionListener(this) ;
this.add(b) ;
}
public void actionPerformes(ActionEvent e)
{
system.out.println("pressed");
//This works
}
}
public class Window extends JFrame implements MouseAdapter
{
menu m;
public Window()
{
m = new menu() ;
this.setBounds(0,0,1000,1000) ;
this.addMouseListener(this) ;
this.add(m) ;
this.setVisible(true) ;
}
public void mouseClicked(MouseEvent e)
{
system.out.println(e.getSource());
//doesnt work
}
public static void main(String[] args)
{
Window w = new Window() ;
}
}
A MouseListener
added to a JFrame
will not fire for every component contained in the JFrame
.
You should make your main
class the ActionListener
for the buttons in your menu
class and then the ActionEvent
will contain the "source".
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
public class MousLsnr extends JFrame implements ActionListener {
public MousLsnr() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
MenuPanel menuPanel = new MenuPanel();
menuPanel.addActionListenerForButtons(this);
add(menuPanel);
pack();
setLocationRelativeTo(null);
setVisible(true);
}
public void actionPerformed(ActionEvent actnEvnt) {
System.out.println(actnEvnt.getSource());
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> new MousLsnr());
}
}
class MenuPanel extends JPanel {
private JButton button1;
private JButton button2;
public MenuPanel() {
button1 = new JButton("One");
button2 = new JButton("Two");
add(button1);
add(button2);
}
public void addActionListenerForButtons(ActionListener listener) {
button1.addActionListener(listener);
button2.addActionListener(listener);
}
}