开发者

Java: pass an event to another component

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


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.


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() + ".");
        }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜