我正在使用某种菜单创建应用程序,但是我的代码有问题。
我有2个班级:第一个班级是菜单班级。此类扩展了JPanel,菜单具有几个按钮,每个按钮都有一个ActionListener。第二类是主类,它扩展了JFrame。
我正在主类中创建菜单类的实例。我在JFrame中添加了mouseListener,并试图在每次单击鼠标时打印事件。不幸的是,当我单击菜单中的按钮之一时,菜单内的ActionListener可以工作,但是JFrame上的mouseEvent不起作用(我也尝试在菜单中使用mouseListener,但它不起作用)。
我的目标是从JFrame类中获取菜单中按下的按钮(源)。感谢您的帮助!
示例:
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() ;
}
}
添加到MouseListener
的JFrame
将not触发JFrame
中包含的每个组件。
您应将main
类的按钮设为ActionListener
,然后将menu
包含“源”。
ActionEvent
请提供一些源代码:)