Skip to main content

Events help

1 reply [Last post]
zed
Offline
Joined: 2004-05-20
Points: 0

Hi...

I need some help registering events. I have a JFrame and in that there are some panels. Now one of the panels has a couple of buttons (plus many other stuff). Since there was a lot of code for this I put this panel in a different class and just made an object and added it in the main JFrame. The problem is when I click a button I want the event sent to the main JFrame (so then depending on the button pressed ill add the new panel and remove the other) and not within that panel. Now since I have made an object out of this panel i'm having problems sending the event back to the parent.

Thanks for the help.

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
acechase
Offline
Joined: 2003-12-02
Points: 0

Hi,

One quick solution is to make a public getButton method for your panel object, and then add your JFrame as a listener to the button.

With Swing's event model, events can be sent anywhere you want, but you have to register to listen for them first. That means the real trick is being able to access the object you want to listen to events from the object which you want to do the listening. That is why your new JPanel class needs to have a getButton method, because that will allow you JFrame class, which has access to the JPanel object, to get access to the button. So, assuming you make a getButton method for your JPanel object, your code in the JFrame class would look like this:
[code]
MyJPanel panel = new MyJPanel() //or however you initialize your object
panel.getButton().addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
//your button event code
}
});
[/code]

and voila, you have the button event being passed to the JFrame.

Hope this helps,
Andrew