Java - 如何在单击时动态添加Swing组件到GUI?

26

我希望做的是类似于在电子邮件中添加附件的原理,您可以单击一个按钮,然后会打开一个新的浏览框,从而增加您可以拥有的独立附件数量。

我还比较新,如果有人能向我指出一个示例,那就更好了。


你可以像静态方式一样做,但根据你想要做什么,可能会有更好的解决方案。 - khachik
5个回答

40

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

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

7
据我所知,“revalidate()”和/或“validate()”应该跟随“repaint()”(否则更改不会反映),另外使用“validate()”是多余的,因为“revalidate()”会调用“validate()”。 - David Kroukamp
在调用validate()revalidate()之后,不一定总是需要调用repaint()。虽然我不知道什么情况下需要调用它...但是在我的应用程序中有这样一个情况,如果没有调用validate()revalidate()repaint(),当添加组件时窗口不会重新绘制。只需添加validate()即可显示新组件。 - Jason
@jmj - 感谢您的解决方案。实际上,当我们在actionPerformed方法内没有其他任务要执行时,它是有效的。但是,如果我有其他任务要执行,首先它会执行这些任务,然后在最后一刻将Button添加到panel中。我希望是相反的情况。首先应该将Button添加到Panel中,然后为该actionperformed方法执行其他任务。 - Karthikeyan

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


2

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

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

1

panel.add(button);

panel.revalidate();

panel.repaint();


1
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<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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接