Java – communication between two jpanels

I have this "main" panel (let's call it AAA) and borderlayout, as well as two panels (BBB and CCC):

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

The 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 the user enters a number in txtnum and presses "OK", the panel CCC shall fill in an appropriate number of rows for data input Each line should contain two text fields, two drop-down lists and a check box If the user enters some large numbers, all projects will be fine in JScrollPane

My question: how can I implement an action listener in BBB? I don't know what number the user entered Therefore, I don't know the exact number of rows in the GridLayout of CCC (I only know that it should have 5 columns) Can I modify its layout from the listener in BBB? How do I add components from the listener in panel BBB to panel CCC?

Of course, if you have a better solution (without two separate panels), please tell me:)

Solution

You may think of this mistake Perhaps it's better not to think about two communicating jpanels, but simply two communicating objects that will communicate with any other two objects - through methods that affect the state By having an object call another object's methods and publish its information to another object, you can push the information from one object to another, or you can pull it from one object to another by using observer design mode With one of a variety of available listeners Myself, I like to use propertychangelistener Therefore, observation objects will accept listeners that will be notified once their state is changed, and then these observers will call the observed's public methods to extract the changed information

For example, look at the code in this answer, or even better, the answer to this question

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>