首页 > 解决方案 > 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() ;
    } 
} 

标签: javaswingactionlistenermouselistener

解决方案


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);
    }
}

推荐阅读