Java Swing add/remove jButtons on runtime(Java Swing 在运行时添加/删除 jButtons)
问题描述
我的应用程序有一个模块,它允许用户在运行时在 jLayeredpane 上添加 jButtons.我想向这个动态添加的内容添加动作侦听器,并且我必须提供在运行时删除动态添加的按钮的访问权限.有没有办法做到这一点?
My application has a module which allows the user to add jButtons on the jLayeredpane during runtime. I want to add action listeners to this dynamically added contents and also i have to provide access to delete the dynamically added buttons during runtime. Is there any way to do this ?
private Map<String, JButton> dynamicButtons;
public void addButton(String name) {
    JButton b = new JButton(name);
    b.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });
    jLayeredPane2.add(b);
    dynamicButtons.put(name, b);
    jLayeredPane2.invalidate();
}
public void removeButton(String name) {
    JButton b = dynamicButtons.remove(name);
    jLayeredPane2.remove(b);
    jLayeredPane2.invalidate();
}
推荐答案
原始答案 总体上不错,但在这种情况下做得不同
为了跟踪任意数量的添加 JButtons,您需要将它们保存在一个列表中.
In order to keep track of an arbitrary number of added JButtons, you will need to keep them in a list.
因此,在您创建一个新按钮、为其添加侦听器并将其添加到窗格后,您需要将该新按钮保存在一个列表中.
So, after you create a new button, add the listeners to it, and add it to the pane, you then need to save that new button in a list.
这样您就可以跟踪您添加的所有按钮.
That way you can keep track of all of the buttons you have added.
您还可以使用 Map 将按钮名称映射到按钮.
You could also use a Map<String, JButton> that maps a button name to the button.
例子:
private Map<String, JButton> dynamicButtons;
public void addButton(String name) {
    JButton b = new JButton(name);
    b.addActionListener(someAction);
    yourPanel.add(b);
    dynamicButtons.put(name, b);
    yourPanel.invalidate();
}
public void removeButton(String name) {
    Button b = dynamicButtons.remove(name);
    yourPanel.remove(b);
    yourPanel.invalidate();
}
<小时>
以下是一个完整的类,可让您动态添加和删除按钮.这不完全是你想要的,但它应该让你真正接近.
The following is a full class that lets you add and remove buttons dynamically. It's not exactly what you want, but it should get you really close.
您的具体案例的代码:
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class ExampleFrame extends JFrame {
    private JButton add, remove;
    private JPanel dynamicButtonPane, addRemovePane;
    private boolean waitingForLocationClick;
    public ExampleFrame() {
        super("Dynamic button example");
        waitingForLocationClick = false;
        add = new JButton("Add Button");
        add.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addButton(JOptionPane
                        .showInputDialog("Name of the new button:"));
            }
        });
        remove = new JButton("Remove Button");
        remove.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                lookingToRemove = true;
            }
        });
        JPanel mainPane = new JPanel(new BorderLayout());
        dynamicButtonPane = new JPanel();
        dynamicButtonPane.setLayout(null);
        dynamicButtonPane.setPreferredSize(new Dimension(300, 300));
        addRemovePane = new JPanel();
        addRemovePane.add(add);
        addRemovePane.add(remove);
        mainPane.add(dynamicButtonPane, BorderLayout.NORTH);
        mainPane.add(addRemovePane, BorderLayout.SOUTH);
        add(mainPane);
        pack();
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
        dynamicButtonPane.addMouseListener(pointSelectorListener);
    }
    private JButton buttonToPlace;
    public void addButton(String name) {
        JButton b = new JButton(name);
        b.setActionCommand(name);
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (lookingToRemove) {
                    if (e.getSource() instanceof JButton) {
                        dynamicButtonPane.remove((Component) e.getSource());
                        dynamicButtonPane.validate();
                        dynamicButtonPane.repaint();
                    }
                } else
                    JOptionPane.showMessageDialog(ExampleFrame.this, "This is " + e.getActionCommand());
            }
        });
        waitingForLocationClick = true;
        lookingToRemove = false;
        buttonToPlace = b;
    }
    public void putButtonAtPoint(Point p) {
        System.out.println("Placing a button at: " + p.toString());
        dynamicButtonPane.add(buttonToPlace);
        buttonToPlace.setBounds(new Rectangle(p, buttonToPlace
                .getPreferredSize()));
        dynamicButtonPane.validate();
        buttonToPlace = null;
        waitingForLocationClick = false;
    }
    private boolean lookingToRemove = false;
    private final MouseListener pointSelectorListener = new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            if (waitingForLocationClick) {
                putButtonAtPoint(e.getPoint());
            } else {
                System.out.println("Not in waiting state");
            }
        }
    };
    public static void main(String[] args) {
        new ExampleFrame();
    }
}
                        这篇关于Java Swing 在运行时添加/删除 jButtons的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java Swing 在运行时添加/删除 jButtons
				
        
 
            
        - Java包名称中单词分隔符的约定是什么? 2022-01-01
 - value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
 - Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
 - 从 finally 块返回时 Java 的奇怪行为 2022-01-01
 - Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01
 - 将log4j 1.2配置转换为log4j 2配置 2022-01-01
 - Eclipse 插件更新错误日志在哪里? 2022-01-01
 - Jersey REST 客户端:发布多部分数据 2022-01-01
 - 如何使用WebFilter实现授权头检查 2022-01-01
 - C++ 和 Java 进程之间的共享内存 2022-01-01
 
						
						
						
						
						