Communication between two JPanels

2019-02-22 03:38发布

问题:

I have this "main" panel (let's call it AAA) with BorderLayout, and two panels (BBB and CCC) in it:

public class AAA extends JPanel {
    BBB pnlNorth = new BBB();
    CCC pnlCenter = new CCC();
    public AAA(){
        setLayout(new BorderLayout());
        add(pnlNorth,BorderLayout.NORTH);
        add(pnlCenter,BorderLayout.CENTER);        
    }
}

Panel CCC is currently empty, with GridLayout.

My panel BBB looks like this:

public class BBB extends JPanel {
    public BBB (){
        JLabel labNum = new JLabel("Number of items: ");
        JTextField txtNum = new JTextField();
        JButton cmdOK = new JButton("OK");
        txtNum.setColumns(5);
        cmdOK.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                /* ???????????? */
            }
        });
        add(labNum);
        add(txtNum);
        add(cmdOK);        
    }
}

When a user enters a number in txtNum and presses "OK", panel CCC should be populated with appropriate number of rows for data input. Each row should contain two text fields, two drop-down lists and a checkbox. It would be nice if all the items would be in a JScrollPane, if the user enters some large number.

My question: How should I implement the action listener in BBB? I have no idea what number will be typed in by the user. Therefore, I don't know the precise number of rows in CCC's GridLayout (I just know it should have 5 columns). Can I modify its layout from the listener in BBB? And how can I add components to the panel CCC from the listener in the panel BBB?

Of course, if you have better solution (without two separate panels), let me know :)

回答1:

You may be thinking about this wrong. It's perhaps better to think not of two JPanel's that are communicating, but rather more simply two objects that are communicating, and they will communicate just the same as any other two objects -- via methods that affect state. This information can be pushed from one object to the other by having the one object call the methods of the other and publish its information to it, or it can be pulled from one object to another by using the observer design pattern such as can be achieved with one of the various listeners that are available. Myself, I like using a PropertyChangeListener for this. So the observed object will accept listeners that are notified once its state has been changed, and these observers will then call public methods of the observed to extract the changed information.

For example, please check out the code in this answer or perhaps even better the answer to this question.



回答2:

I managed to do this. I simply passed the Center panel as a parameter in the North panel's constructor. It works perfectly. Thank you all for the answers :)