Java:单击按钮时如何删除特定对象 [英] Java: how to remove specific object when button clicked
问题描述
我试图通过单击一个对象的按钮来删除它,但是当我单击面板内的按钮时,它会删除上次创建的面板.
I'm trying to remove an object by clicking it's button, but what happens is when I click the button inside the panel it removes the last created panel.
问题是如何移除我想要的特定面板?
Question is how will I remove the specific panel that I want?
这是我的代码:
public class TimerPractice extends JFrame implements ActionListener
{
JPanel main=new JPanel();
JPanel gui=new JPanel();
JButton btnadd=new JButton("Add Timer");
JPanel order=new JPanel();
public TimerPractice()
{
main.setLayout(new BorderLayout());
gui.setLayout(new FlowLayout());
main.add(btnadd, BorderLayout.NORTH);
main.add(gui,BorderLayout.CENTER);
add(main);
btnadd.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
//addPanel();
//System.out.print(x);
addPanel();
revalidate();
repaint();
}
});
main.add(gui);
}
public void addPanel()
{
Border blackline=BorderFactory.createLineBorder(Color.BLACK);
order=new JPanel();
order.setPreferredSize(new Dimension(200,300));
order.setLayout(new BorderLayout());
TitledBorder title=BorderFactory.createTitledBorder(blackline);
title.setTitleJustification(TitledBorder.LEFT);
order.setBorder(title);
addBtn();
gui.add(order);
}
public void addBtn()
{
JButton remove=new JButton("Remove");
order.add(remove, BorderLayout.SOUTH);
remove.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
gui.remove(order);
revalidate();
repaint();
}
});
}
public static void main(String args[])
{
TimerPractice p=new TimerPractice();
p.setSize(1000,800);
p.setVisible(true);
p.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
p.setLocationRelativeTo(null);
}
}
推荐答案
每次添加新的 order
面板时,都会重新分配对 order
的引用以指向最后创建的JPanel
,这意味着当你说remove(order)
时,它只知道如何删除你创建的最后一个面板...
Each time you add a new order
panel, you are reassigning the reference to order
to point to the last created JPanel
, this means that when you say remove(order)
, it only knows how to remove the last panel you created...
长答案,将每个 order
面板分成它自己的、自包含的和托管的实体,这样你就不会遇到你现在遇到的参考问题......
Long answer, separate each order
panel into it's own, self contained and managed entity, this way you won't run into the reference issues you are having right now...
简短回答,从 ActionEvent
...
public void actionPerformed(ActionEvent e)
{
Object source = e.getSource();
if (source instanceof Component) {
Component comp = (Component)source;
gui.remove(comp.getParent());
revalidate();
repaint();
}
}
您可以使用 Action
生成一个自包含的工作单元,您将传递 order
的当前实例的引用,这将允许 Action
维护它自己的引用与TimerPractice
类
You could use an Action
to generate a self contained unit of work, which you would pass a reference of the current instance of order
, this would allow the Action
to maintain it's own reference separate from the TimerPractice
class
这篇关于Java:单击按钮时如何删除特定对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!