Java访问通过MouseEvent单击了JButton的公共方法(Java access clicked JButton's public methods by the MouseEven

编程入门 行业动态 更新时间:2024-10-07 10:14:08
Java访问通过MouseEvent单击了JButton的公共方法(Java access clicked JButton's public methods by the MouseEvent)

我想在/我的鼠标事件中传递/访问参数。

public class Button extends JButton{ public int fileID=6; public int getButtonID(){ return fileID; } } [View.java] Button1.addMouseListener(controller); [Controller.java] public void mousePressed(MouseEvent e) { System.out.println(e.getButtonID()); //not working System.out.println(e.getSource().getButtonID()); //not working

基本上,我需要的是对点击按钮的某种引用,所以我可以得到它的fileID。 这可能吗? 每个按钮代表一个文件,我想让用户删除它。 请告诉我是否有更好的方法来获取用户点击的信息。

谢谢

I want to pass/access a parameter to/in my Mouse Event.

public class Button extends JButton{ public int fileID=6; public int getButtonID(){ return fileID; } } [View.java] Button1.addMouseListener(controller); [Controller.java] public void mousePressed(MouseEvent e) { System.out.println(e.getButtonID()); //not working System.out.println(e.getSource().getButtonID()); //not working

Basically, what I need is some kind of reference to the clicked button so I can get its fileID. Is this possible? Each button represents a file and I want to give the user the possibility to delete it. Please tell me if there is a better way to obtain the information where the user has clicked.

Thanks

最满意答案

如果你可以确定你的Controller只会被添加到Button ,那么为什么不将e.getSource()为Button呢?

((Button) e.getSource()).getButtonID()

但是,您也可以在Controller的构造函数中使用Button并使用它(您无法获得ClassCastException ,因为它必须是Button 。)

If you can be sure your Controller will only ever be added to a Button, then why not cast e.getSource() to Button?

((Button) e.getSource()).getButtonID()

However, you can also take the Button in the constructor of Controller and use that (you can't get a ClassCastException that way as it has to be a Button.)

更多推荐

本文发布于:2023-07-09 10:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1085534.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:单击   方法   JButton   Java   MouseEvent

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!