将事件从孩子传递给父母

时间:2014-03-05 23:46:51

标签: java swing jpanel mouseevent

是否可以将事件从实例类传递给父类?

我有一个JFrame,其容器有两个JPanel。上面板包含另一个较小的JPanel,并且我已成功设置MouseListener以在单击小面板时执行命令。我想在单击小面板时在底部面板上显示文本。问题是事件处理是在上面板类中完成的,它不能访问JFrame上其他面板的实例。

以下是主窗口代码:

public CalendarWindow() {
    // Set global variables
    size = new Dimension(600,600);
    setMinimumSize(size);

    // Set default window layout and behaviour
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     
    setLayout(new BorderLayout());
    Container c = getContentPane();

    // Create panels and components
    eventPanel = new EventPanel(new Dimension(size.width - 30, size.height/3));     
    CalendarPanel calendarPanel = new CalendarPanel(new Dimension(size.width - 30, size.height*2/3));


    // Add components and panels to content pane
    c.add(eventPanel, BorderLayout.SOUTH);
    c.add(calendarPanel, BorderLayout.NORTH);
}

这是calendarPanel中的事件处理:

boxes[i][j].addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        if(selectedBox != null)
            selectedBox.unselect();
        selectedBox = (DateBox)e.getSource();
        selectedBox.getParent().getParent().dispatchEvent(e);


        if(SwingUtilities.isRightMouseButton(e)) {
            rightClickMenu menu = new rightClickMenu();
            menu.show(e.getComponent(), e.getX(), e.getY());
            menu.newEvent.addMouseListener(new MouseAdapter() {
                public void mousePressed(MouseEvent e) {
                    selectedBox.addCalendarEvent(new CalendarEvent("Kaupa mjólk", 14, 15));
                }
            });
        }
    }
});

box变量是一种扩展JPanel的类型。如何使CalendarWindow在上面板中检测到鼠标单击?

1 个答案:

答案 0 :(得分:2)

在父类中创建一个更改文本的方法,
并将父类传递给eventPanel
(添加参数,例如。 public eventPanel(CalendarWindow cw)
然后传递它, new eventPanel(this)),
然后在 eventPanel cw.themethod())中调用父方法