adding components dynamically in a JPanel

前端 未结 2 951
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 15:13

how can i add components dynamically in a jpanel? I am having add button when i click the button the components should be added to the JPanel.

my question is that ad

相关标签:
2条回答
  • 2020-12-06 15:50

    Use an ActionListener, you can use an anonymous class like this:

    JPanel myJPanel = new JPanel();
    
    ...
    
    b = new Button("Add Component");
    b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            JLabel someLabel = new JLabel("Some new Label");
            myJPanel.add(someLabel);
            myJPanel.revalidate();
        }
    });
    
    0 讨论(0)
  • 2020-12-06 16:04

    Just as you always do, except that you have to call:

    panel.revalidate();
    

    when you are done, since the container is already realized.

    0 讨论(0)
提交回复
热议问题