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?
Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets for building optimized window based applications. It is a part of the JFC( Java Foundation Classes). It is build on top of the AWT API and entirely written in java. It is platform independent unlike AWT and has lightweight components.
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(); } }
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); }
Component was not visible until setSize()
was called:
component.setSize(100,200);
jPanel.add(component);
jPanel.revalidate();
jPanel.repaint();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With