views:

168

answers:

2

Sorry I don't know if this is very clear, but I'm pretty new to Java.

So I have a JFrame with a BorderLayout containing a JPanel and a JButton.

What I want to do is when something happens in my JPanel, I want for example change the text of the JButton, or enable/disable it. How would I do that? How can I access the JButton from the JPanel? I know some ways of doing it but I don't think they're the best way to do it.

What would be the best way to do this?

Thanks in advance

A: 

You have to listen to an event on your JPanel. JPanels can listen to key presses (KeyListener ), mouse clicks (MouseListener), and mouse movements (MouseMovementListener). Which one are you interested in?

Once you know what you want to listen to, you have to write and register a listener, and change something in the JButton. For example:

// define JButton jb, JPanel jp, put one inside the other so that there is some
// free space to click on around the JPanel; declare both as final.
...

// listen to mouse clicks on the panel and updates the button's label
jp.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            jb.setText(jb.getText() + ".");
        }
});
tucuxi
Yes I'd like something like that, but is it possible to listen to a custom event somehow? I want to trigger this event when reaching a specific part of my JPanel code
John
You can call `jb.setText("I reached this line")` wherever you want in your JPanel code. You do not need events for that. If you want to generate synthetic UI events (that is, events that did not actually happen), have a look at `java.awt.Robot` -- but I doubt that you want that, since you say that you are beginning with Java.
tucuxi
A: 

The most simple case is when your JPanel instance and JButton instance "see" each other in your code i.e.:

JButton button = new JButton ("Click me");
JPanel panel = new JPanel ();
...
container.add (button);
container.add (panel);

In that case you can add some event listener to your panel (or to your button) and change the second component from event handler:

panel.addMouseListener (new MouseAdapter () {
   public void mouseClicked (MouseEvent e) {
      button.setText ("new text");
   }

});

The only thing you should count here is that you should use final modifier near button declaration (due to java doesn't have real closures):

final JButton button = new JButton ("Click me");
JPanel panel = new JPanel ();

panel.addMouseListener (new MouseAdapter () {
   ....
});

More complicated case is when your components don't know about each other or when system state is changed and components state (like button name or something more serious) should be changed too. In this case you should consider using MVC pattern. Here is a very nice tutorial from JavaWorld: MVC meets Swing.

Roman
Thank you. I think that MVC is what I need.
John