Communicating between JPanels

丶灬走出姿态 提交于 2019-12-12 05:38:47

问题


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.


回答1:


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();
               }});
            }});


来源:https://stackoverflow.com/questions/9759792/communicating-between-jpanels

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!