gpt4 book ai didi

java - 点击 "delete"按钮后如何删除按钮?

转载 作者:行者123 更新时间:2023-11-30 03:02:16 24 4
gpt4 key购买 nike

除了删除部分之外,我的程序似乎运行良好。每次我单击“删除”按钮时,它都会自行删除。所以我的问题是,单击“删除”按钮后如何删除所选按钮?这是我的代码片段:

public class DeleteButton extends JFrame implements ActionListener 
{
JButton b18a = new JButton("Delete");
JPanel panel = new JPanel();
panel.add(b18);

class ClickListenerTwo implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
JButton buttonThatWasClicked = (JButton) e.getSource();
Container parent = buttonThatWasClicked.getParent();
parent.remove(buttonThatWasClicked);
parent.revalidate();
parent.repaint();
}
}
}
ActionListener b18aClicked = new ClickListenerTwo();
b18a.addActionListener(b18aClicked);

P.S - 我正在谈论的这个选定按钮是在运行时创建的,因此如果可能的话,我也想在运行时删除它。谢谢!

最佳答案

因此,假设您需要先单击“其他”按钮,则可以使用实例字段来维护对“最后”单击的按钮的引用,然后在单击删除按钮时使用该引用

例如...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}

JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}

public class TestPane extends JPanel {

private JButton lastButton;

public TestPane() {
JPanel grid = new JPanel(new GridLayout(8, 8));
for (int index = 0; index < 8 * 8; index++) {
JButton btn = new JButton(Integer.toString(index + 1));
btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
lastButton = btn;
}
});
grid.add(btn);
}

JButton delete = new JButton("Delete");
delete.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (lastButton != null) {
lastButton.getParent().remove(lastButton);
grid.revalidate();
grid.repaint();
}
lastButton = null;
}
});

setLayout(new BorderLayout());
add(grid);
add(delete, BorderLayout.SOUTH);
}

}

}

就个人而言,JToggleButton 会提供更好的用户体验

关于java - 点击 "delete"按钮后如何删除按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35664320/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com