26

What I am looking to do is a similar principle to adding attachments to emails, you can click a button and a new browse box would open increasing the number of separate attachments you can have.

I'm fairly new so if someone could point me towards an example?

akjoshi
  • 15,374
  • 13
  • 103
  • 121
slex
  • 855
  • 2
  • 10
  • 20
  • You can do it as you do it statically, but they may be nicer solutions depending on what you want to do. – khachik Nov 25 '10 at 18:26

5 Answers5

40

Sample code to add Buttons on the fly dynamically.

panel.add(new JButton("Button"));
validate();

Full code:

import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JPanel;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import java.awt.FlowLayout;
import java.awt.BorderLayout;

public class AddComponentOnJFrameAtRuntime extends JFrame implements ActionListener {

    JPanel panel;

    public AddComponentOnJFrameAtRuntime() {
        super("Add component on JFrame at runtime");
        setLayout(new BorderLayout());
        this.panel = new JPanel();
        this.panel.setLayout(new FlowLayout());
        add(panel, BorderLayout.CENTER);
        JButton button = new JButton("CLICK HERE");
        add(button, BorderLayout.SOUTH);
        button.addActionListener(this);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(500, 500);
        setVisible(true);
    }

    public void actionPerformed(ActionEvent evt) {
        this.panel.add(new JButton("Button"));
        this.panel.revalidate();
        validate();
    }

    public static void main(String[] args) {
        AddComponentOnJFrameAtRuntime acojfar = new AddComponentOnJFrameAtRuntime();
    }
}
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 7
    As far as I know, `revalidate()` and/or `validate()` should be followed by `repaint()` (or changes wont be refelcted) also using `validate()` is redundant as `revalidate()` calls `validate()` – David Kroukamp Jan 04 '13 at 18:51
  • Calling `repaint()` after `validate()` or `revalidate()` is not always necessary. Though I do not know the conditions for when it is required... I have a case in my app where without `validate()`, `revalidate()`, and `repaint()` the window does not redraw when a component is added. Just adding `validate()` causes the new component to be displayed. – Jason Aug 17 '17 at 15:16
  • @jmj - Thanks for the solution., actually its works when we dont have other task to perform inside `actionPerformed` method. But if i have some other task to perform, firstly its performing those task and at last moment `Button` is adding to the `panel`. I was expecting in the reverse case. First it should add `Button` in the `Panel` and perform other task for that `actionperformed` method. – Karthikeyan Oct 19 '21 at 14:25
10
public static void main(String[] args) {

    final JFrame frame = new JFrame("Test");
    frame.setLayout(new GridLayout(0, 1));

    frame.add(new JButton(new AbstractAction("Click to add") {
        @Override
        public void actionPerformed(ActionEvent e) {

            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    frame.add(new JLabel("Bla"));
                    frame.validate();
                    frame.repaint();
                }
            });
        }
    }));

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
}

screenshot

dacwe
  • 43,066
  • 12
  • 116
  • 140
2

Component was not visible until setSize() was called:

component.setSize(100,200);
jPanel.add(component);
jPanel.revalidate();
jPanel.repaint(); 
Magnilex
  • 11,584
  • 9
  • 62
  • 84
Vidura Adikari
  • 549
  • 4
  • 7
1

panel.add(button);

panel.revalidate();

panel.repaint();

Raj Trivedi
  • 557
  • 7
  • 18
1

Java : Dynamically add swing components

for Example : count=3
//Java Swing: Add Component above method
public void  dya_addcomp(int count)
{
//Dynamicaly Delete Image_icon
 BufferedImage Drop_Tablefield = null;
 try {
     Drop_Tablefield = ImageIO.read(this.getClass().getResource("/images/drop.png"));
 } catch (IOException ex) {
     msg(" Error: drop and edit icon on Table, "+ex);
 }
 //count Items:  3 times for loop executed..
 for(int i=0;i<count;i++)
 {
     //cnt++;
     //lblcount.setText("Count : "+cnt);
     JTextField txtcolnm=new JTextField("",20);
     JComboBox cmbtype=new JComboBox();
     JTextField txtcolsize=new JTextField("",20);

     JButton Drop_Table_Field = new JButton(new ImageIcon(Drop_Tablefield));

     cmbtype.addItem("INTEGER"); cmbtype.addItem("FLOAT");
     cmbtype.addItem("STRING");  cmbtype.addItem("BOOLEAN");

     colnamepanel.add(txtcolnm);   colnamepanel.add(cmbtype);
     colnamepanel.add(txtcolsize); colnamepanel.add(Drop_Table_Field);

     colnamepanel.setAutoscrolls(true);

     //refresh panel
     colnamepanel.revalidate();
     colnamepanel.repaint();

     //set the layout on Jpanel
     colnamepanel.setLayout(new FlowLayout(FlowLayout.LEFT,5,0));
  }//end for loop
 }//end method
Chetan Bhagat
  • 610
  • 6
  • 21