java - Java Swing - 在 JPanel 中获取源代码
问题描述
我正在创建一个带有某种菜单的应用程序,但我的代码有问题。
我有 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() ;
}
}
解决方案
AMouseListener
添加到 aJFrame
不会为包含在JFrame
.
你应该让你的main
班级成为班级ActionListener
中的按钮,menu
然后ActionEvent
将包含“来源”。
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);
}
}
推荐阅读
- c# - 如何将 ListBox 项添加到 DataGridView 列标题
- python - 线性回归:ValueError:x 和 y 必须具有相同的第一维,但具有形状 (10, 1) 和 (1, 1)
- java - 添加数字的第一个和最后一个数字
- javascript - 如何将日期时间格式数据从 json 导入和导出到 nosql(firestore)
- sql-server - 在同一台服务器上并行运行多个 SSIS 项目
- html - CSS:位置:固定移位 div
- c++ - C++ 连接器:使用 MariaDB 插入日期时间
- python - 具有内置输入函数的类方法(Python)
- ios - 必须先配置默认 FirebaseApp 实例,然后才能初始化 defaultFirebaseApp 实例
- reactjs - useEffect 未触发