Jonathan
Jonathan

Reputation: 61

Communicating between JPanels

First off, I'm new to Java, so please be gentle.

I have a JFrame which has two 'JPanels', one of which is a separate class (i've extended the JPanel). Ideally I'd like to 'dispatch and event' or notify the other JPanel object on the JFrame.

I have an array of JButtons in the custom JPanel class, which i'd like to add an event listener to. Upon clicking the JButton, i'd like to change something on the other JPanel.

I'm really not sure how to do this, so I moved the event handler into the JFrame class, and tried to do the following:

panel.buttonArray[i][j].addActionListener(this);

However, doing that didn't work at all. Annoyingly, Eclipse didn't complain either...

Any tips on how I can achieve this?

This was horribly explained, sorry.

Upvotes: 1

Views: 1281

Answers (1)

Java42
Java42

Reputation: 7706

Think of this not in terms of panels but in terms of objects. As long an object, lets say it has a name of object77, has a reference to the other object, call it object42, object77 can call methods on object42.

  object77.methodInObject42();

  panel77.methodInPanel42();

As for the event handler, then

   buttonOnPanelXX.addActionListener(new ActionListener(){
       public void actionPerformed(ActionEvent e) {
             panel77.methodInPanel42();
       }});

or even better...

    button.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e) {
            SwingUtilities.invokeLater(new Runnable(){
               public void run() {
                  panel77.methodInPanel42();
               }});
            }});

Upvotes: 2

Related Questions