java – 如何在点击时动态添加swing组件给gui?

我想要做的是向电子邮件添加附件的类似原则,您可以单击一个按钮,打开一个新的浏览框,增加您可以拥有的单独附件的数量。

我是新人,所以如果有人能指出我的榜样?

用于动态添加按钮的示例代码。

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

完整代码:

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

截图

在调用setSize()之前,组件不可见:

 component.setSize(100,200); jPanel.add(component); jPanel.revalidate(); jPanel.repaint(); 

panel.add(按钮);

panel.revalidate();

panel.repaint();

Java:动态添加swing组件

 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