java - 如何在点击时动态地将swing组件添加到gui?

sle*_*lex 23 java user-interface swing

我所希望做的是一个类似的原则,以添加附件的电子邮件,你可以点击一个按钮和一个新的浏览框将打开上升单独的附件,你可以拥有的数量.

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

Jig*_*shi 35

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

panel.add(new JButton("Button"));
validate();
Run Code Online (Sandbox Code Playgroud)

完整代码:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 据我所知,`revalidate()`和/或`validate()`后跟`repaint()`(或更改不会被重新连接)也使用`validate()`冗余为`revalidate()`调用`validate()` (6认同)

dac*_*cwe 9

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);
}
Run Code Online (Sandbox Code Playgroud)

截图