java - 如何在点击时动态添加swing组件给gui? [英] java - How would I dynamically add swing component to gui on click?

查看:297
本文介绍了java - 如何在点击时动态添加swing组件给gui?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

Sample code to add Buttons on the fly dynamically.

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




  • 资源

    • Resource
    • 这篇关于java - 如何在点击时动态添加swing组件给gui?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆