Java 使用带有按钮的面板的ArrayList访问困难
我的问题是:如何获取CustomPanel的对象,以便能够访问它的字段(因为在我的实际程序中,我有更多的字段在其中),并且能够从ArrayList中删除它 我不知道如何在类窗口中实现ActionListener,以某种方式获取Arraylist中的对象,其中包含按下的按钮Java 使用带有按钮的面板的ArrayList访问困难,java,arraylist,actionlistener,Java,Arraylist,Actionlistener,我的问题是:如何获取CustomPanel的对象,以便能够访问它的字段(因为在我的实际程序中,我有更多的字段在其中),并且能够从ArrayList中删除它 我不知道如何在类窗口中实现ActionListener,以某种方式获取Arraylist中的对象,其中包含按下的按钮 //imagine this comment in above code aLCustomPanel.get(aLCustomPanel.size()-1).getButton().addActionListener(new
//imagine this comment in above code
aLCustomPanel.get(aLCustomPanel.size()-1).getButton().addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
button_IwantToDeleteYou(e); //here I want to remove the panel, containing the button that got pressed from the above ArrayList, which is located in Class Window
}
});
另外,我想知道我是否能够在CustomPanel类中实现ActionListener,它可以影响作为类窗口实例的对象的行为
我有以下代码:
public class Window extends JFrame{
ArrayList<CustomPanel> aLCustomPanel = new ArrayList();
JPanel jp = new JPanel();
public Window() {
for(int i=0;i<5;i++){
aLCustomPanel.add(new CustomPanel());
//here I could put the code from the 1 edit - see below
jp.add(aLCustomPanel.get(i));
}
this.add(jp);
}
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Window().setVisible(true);
}
});
}
}
class CustomPanel extends JPanel {
private JButton button;
public CustomPanel(){
button = new JButton("button");
this.add(button);
}
public JButton getButton(){
return this.button;
}
}
编辑2: 添加了一个缺少的括号并修复了一些错误,代码现在应该可以了。您的代码包含一些“空白”,即缺少代码,我将其填写如下:
JFrame
]方法的调用setDefaultCloseOperation()
和pack()
和setLocationByPlatform()
。我建议您参考javadoc了解这些方法,以便了解它们的功能窗口中为jp
类成员变量设置了布局管理器
CustomPanel
中使用JButton
注册一个ActionListener
,并且该侦听器应该位于您的窗口
类-扩展JFrame
的类中
这是我对你的代码的重写。注意,我将类Window
的名称更改为CusPanel
,以便区分您的类和java.awt.Window
类。并不是说这有什么区别,我只是不喜欢使用来自JDK的类的名称
导入java.awt.Container;
导入java.awt.EventQueue;
导入java.awt.GridLayout;
导入java.awt.event.ActionEvent;
导入java.awt.event.ActionListener;
导入java.util.ArrayList;
导入javax.swing.JButton;
导入javax.swing.JFrame;
导入javax.swing.JPanel;
导入javax.swing.WindowConstants;
公共类CusPanel扩展JFrame实现ActionListener{
私有静态最终整数计数=5;
private ArrayList aLCustomPanel=new ArrayList();
private JPanel jp=new JPanel(new GridLayout(0,COUNT));
公共事务委员会(){
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
for(int i=0;i //aLCustomPanel.remove(父级);我仍然不明白您要“获取”什么对象。你能把它作为变量添加到你的代码中吗?可能像对象iWantGet=//窗口对象
。我想要CustomPanel类型的对象作为某个函数的返回。它已经以元素的形式在我的代码中实现了。所以我想得到ArrayList aLCustomPanel的元素,它包含按下的按钮。是吗现在更清楚了吗?抱歉,如果这很难理解,请给我一个提示,说明哪部分不够理解//这里我想删除上面ArrayList中被按下的按钮,它位于类窗口中。ArrayList有面板,你如何从中删除按钮?首先,你需要发布一个。发布最小数量的代码,我可以复制到我的计算机上,然后编译它,然后运行它。其次,你的问题似乎是一个例子。你为什么要在点击它后删除JButton
?对不起,伙计们,你说得对,我要删除包含按下的按钮的面板。(不是直接删除按钮)我也强烈地感觉到这是一个最小的可复制的例子…我没有把我使用的所有进口产品都放进去,但我认为它们是标准的摆动部件,并且是众所周知的。非常感谢,这正是我所寻找的。很抱歉我的问题很混乱,我真的很难做到这一点。我需要它的原因是:我想能够添加新的球员,但不是吗o一个游戏,并且能够再次删除它们,这就是为什么我需要这个删除按钮。。