Event Handling

Hy!

I have a problem with the listeners.

I have 3 classes:

MainWindow(JFrame) <-- MainMenu(JPanel) <-- MainMenuItem(JPanel)

The whole idea is to make the MainWindow class to sense when a MainMenuItem has changed, like let's say clicked, or changed background,etc. I must mention that JPanel is almost a simulated button.

Or could I share data between the main frame and the simulated button ?

Please guys I really need an advice

[478 byte] By [endera] at [2007-11-26 23:35:08]
# 1

Your MainMenuItem sounds like a component not a panel, so I'd make it a

JComponent not a JPanel.

> The whole idea is to make the MainWindow class to sense when a MainMenuItem

> has changed,

Then make your MainWindow a javax.swing.event.ChangeListener or have it

include such a listener as an instance variable. The MainMenuItem should maintain a list of change listeners whose stateChanged() method is called every time its state is changed (eg its background is changed).

Similarly for mouse clicks - create a java.awt.event.MouseListener and have it listen

for mouse clicks on the MainMenuItem. This is a little easier because a JComponent

already offers a method for adding such listeners.

This is just off the top of my head - you will get better help if you ask in the Swing

forum.

(Also: consider using JButton - or a subclass thereof - for your buttons, as this may

make the event handling easier. In general use Swing components if you can,

and roll your own only when you understand why you can't use the builtin ones,)

pbrockway2a at 2007-7-11 14:56:22 > top of Java-index,Java Essentials,Java Programming...
# 2

Create a listener for events from the menu item, and add it to the menu item. This could be an inner class that knows how to change the frame's state, or it could be the frame itself is a listener.

It sounds like you may be mixing the GUI with the main app logic, which often confuses things. You might do well to segregate them.

paulcwa at 2007-7-11 14:56:22 > top of Java-index,Java Essentials,Java Programming...
# 3

I did some changes in my program and now it works. You were right with the idea of adding a listener from main menu, but I doing that I needed to add a listener to the main menu from the main window. Instead I declared the buttons in the main window and added them a listener from there, and now the menu only arranges them on the screen, while the main window monitors their activities.

Thanks guys for all your help!

endera at 2007-7-11 14:56:22 > top of Java-index,Java Essentials,Java Programming...