Reputation: 329
Is it possible to pass events from an instance class to a parent class?
I have a JFrame with a container that has two JPanels. The upper panel contains another smaller JPanel and I've set up a MouseListener successfully to execute a command when the small panel is clicked. I want to display text on the bottom panel when the small panel is clicked. The problem is that the event handling is done within the upper panel class, which does not have access to the instance of the other panel on the JFrame.
Here is the main window code below:
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);
}
This is the event handling within 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));
}
});
}
}
});
The boxes variable is a type that extends JPanel. How can I make it so that the CalendarWindow detects the mouse click in the upper panel?
Upvotes: 0
Views: 1768
Reputation: 515
Make a method in your parent class that changes the text,
and pass the parent class to the eventPanel
(add a parameter eg. public eventPanel( CalendarWindow cw),
then pass it, new eventPanel(this)),
and then call the method of the parent within the eventPanel (cw.themethod())
Upvotes: 2