Java 动态按钮上的事件侦听器

Java 动态按钮上的事件侦听器,java,arrays,swing,model-view-controller,jbutton,Java,Arrays,Swing,Model View Controller,Jbutton,我已经为此奋斗了一段时间,我正在尝试构建一个利用MVC模式的程序,该模式基于用户输入动态创建按钮网格(nxn)。然而,我无法正确地将侦听器附加到它们 编辑:我的意思是我想处理控制器类内部的事件以符合MVC模式 看法 我试过几种方法,但似乎都不管用,我的结果大多是空指针异常。有什么建议吗?当您进行初始化循环时: for(int x = 0; x < size; x++) { btn_arr[y][x] = new JButton(); btn_arr[y][x].setBackgr

我已经为此奋斗了一段时间,我正在尝试构建一个利用MVC模式的程序,该模式基于用户输入动态创建按钮网格(nxn)。然而,我无法正确地将侦听器附加到它们

编辑:我的意思是我想处理控制器类内部的事件以符合MVC模式

看法


我试过几种方法,但似乎都不管用,我的结果大多是空指针异常。有什么建议吗?

当您进行初始化循环时:

for(int x = 0; x < size; x++)  {
  btn_arr[y][x] = new JButton();
  btn_arr[y][x].setBackground(Color.white);
  GameGUI.add(btn_arr[y][x]);
  btn_arr[y][x].setVisible(true);
  btn_arr[y][x].addActionListener( new YourListener() );
}
for(int x=0;x
根据您目前发布的代码,您似乎可以添加一个呼叫

btn_arr[y][x] = new JButton();
btn_arr[y][x].addActionListener(createActionListener(y, x));
...
用这样的方法

private ActionListener createActionListener(final int y, final int x)
{
    return new ActionListener()
    {
        @Override 
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("Clicked "+y+" "+x);

            // Some method that should be called in 
            // response to the button click:
            clickedButton(y,x);
        }
    };
}

private void clickedButton(int y, int x)
{
    // Do whatever has to be done now...
}

您是否成功进入startBTActionPerformed()方法?是的,它创建了网格。抱歉,在我使用Netbeans创建gui时删除了一些代码,但这不符合MVC模式吗?@ChrisCrossman必须在按钮上附加一些
ActionListener
。这是在按钮上附加
ActionListener
的“最小”方式,并且仍然保留有关单击哪个按钮的信息。这样说:您可以在
单击按钮
方法中仅调用
controller.doSomethingWith(x,y)
。还是你的问题旨在从外部注入ActionListeners?MVC在这一点上有点争议(到底什么是控制器?)。对我来说,每个
ActionListener
都已经是一个小小的控制器。让我们看看其他人是怎么说的。我试着从以下几行中得到一些东西:但由于按钮尚未创建,因此我最终得到了一个空指针。但我明白你的意思。如果找不到其他解决方案,我可能会在视图中添加对控制器的引用。同意Marco的说法。如果希望视图交互提供一些逻辑,则必须将控制器传递到视图中。一旦调用了actionPerformed,您就可以在控制器中调用一个方法来执行逻辑。@Zyn我决定只传递一个对视图的引用,正如Zyn所说的,它确实简化了很多。谢谢你的帮助
btn_arr[y][x] = new JButton();
btn_arr[y][x].addActionListener(createActionListener(y, x));
...
private ActionListener createActionListener(final int y, final int x)
{
    return new ActionListener()
    {
        @Override 
        public void actionPerformed(ActionEvent e)
        {
            System.out.println("Clicked "+y+" "+x);

            // Some method that should be called in 
            // response to the button click:
            clickedButton(y,x);
        }
    };
}

private void clickedButton(int y, int x)
{
    // Do whatever has to be done now...
}