简体   繁体   中英

Java - How to add new JLabel and JTextPane to JPanel when button is pressed

I have a JPanel to which when a button is pressed I want to add a new JLabel and JTextField too. However, I can't seem to get it working.

Is there an issue with my ActionListener, and if not, how could this be achieved?

JPanel south = new JPanel();
JButton add = new JButton("Add");
ActionListener addListener = new ActionListener() {

     @Override
     public void actionPerformed(ActionEvent e) {
           JLabel mL = new JLabel("MOD: ");
           mR.add(mL);
           JTextField mM = new JTextField(10);
           mR.add(mM);
           mR.repaint();

     }

};
add.addActionListener(addListener);
south.add(add);
add(south, BorderLayout.NORTH);

The layout of the mR panel is a grid layout set to allow multiple rows and two columns.

repaint();之前调用mR.revalidate() repaint();

请参阅我对上一个SO问题的回答,以获取一些示例代码,该示例代码将组件动态添加到容器中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM