Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在JButton矩阵中生成事件?_Java_Arrays_Swing_Jbutton_Mouselistener - Fatal编程技术网

Java 如何在JButton矩阵中生成事件?

Java 如何在JButton矩阵中生成事件?,java,arrays,swing,jbutton,mouselistener,Java,Arrays,Swing,Jbutton,Mouselistener,我正在尝试创建一个鼠标侦听器。当我将鼠标悬停在JButton上时,我希望它更改其背景色以及数组中的下一个JButtons。例如,当我悬停在JButton[0][0]上时,它会更改JButton[0][0]、JButton[1][0]、JButton[2][0]等的背景 下面是如何创建JButton数组: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { btn[i][j] = new J

我正在尝试创建一个
鼠标侦听器
。当我将鼠标悬停在
JButton
上时,我希望它更改其背景色以及数组中的下一个
JButton
s。例如,当我悬停在
JButton[0][0]
上时,它会更改
JButton[0][0]
JButton[1][0]
JButton[2][0]
等的背景

下面是如何创建
JButton
数组:

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        btn[i][j] = new JButton();
        btn[i][j].addMouseListener(this);
        btn[i][j].setBackground(Color.black);
        panel.add(btn[i][j]);
    }
}
我试过做
btn[I+1][j].setBackground(Color.black)并设置为蓝色
[1][0]
[2][0]
。。。但不是
[i+1][j]

运行程序时没有错误


上图显示了我正在尝试做的事情。

不需要引用数组——只需更改按钮的状态,按钮将通过
getSource()
返回。e、 g

@Override
public void mouseEntered(MouseEvent me) {
    JButton event = (JButton) me.getSource();
    event.setBackground(Color.blue);
}
同样地,对于鼠标退出

如果需要知道特定鼠标的i和j,则使用嵌套for循环遍历数组

int i = 0;
int j = 0;
for (int i2 = 0; i2 < btn.length; i2++) {
    for (int j2 = 0; j2 < btn[i2].length; j2++) {
        if (event == btn[i2][j2]) {
            i = i2;
            j = j2;
        }
    }
}

// i and j set to appropriate value
inti=0;
int j=0;
for(int i2=0;i2

或者获取并设置按钮的客户端属性,类似于之前所做的。如果您需要更详细的帮助,请创建并发布一个有效的您正在寻找的方法称为
Component.dispatchEvent(AWTEvent e)
,我为此提供了一个一维示例:

package scratch.pad.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;

/**
 * Propagate event to neighbor buttons
 */
public class EventPropagation extends JFrame {

    private List<JButton> buttons = new ArrayList<>();

    private class MouseEventPropagationListener extends MouseAdapter {

        // The event source, for controlling the propagation of the event.
        // To prevent infinite loop, we only dispatch the event to targets when
        // e.getSource() == this.source;
        private JButton source;

        // Targets to propagate the event.
        private java.util.List<JButton> targets;

        public MouseEventPropagationListener(JButton source, JButton ... targets) {
            this.source = source;
            this.targets = Arrays.asList(targets);
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            super.mouseEntered(e);
            // Use this.source because e.getSource() could be different.
            this.source.setBackground(Color.WHITE);
            dispatchEvent(e);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            super.mouseExited(e);
            this.source.setBackground(Color.BLACK);
            dispatchEvent(e);
        }

        private void dispatchEvent(MouseEvent e) {
            if (e.getSource() == source) {
                for (JButton target : targets) {
                    target.dispatchEvent(e);
                }
            }
        }
    }

    public EventPropagation() throws HeadlessException {

        final int n = 10;

        this.setTitle("Event propagation test");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.getContentPane().setLayout(new FlowLayout());

        this.setSize(300, 300);

        this.setResizable(false);

        // Create the buttons
        for (int i = 0; i < n; i++) {
            JButton btn = new JButton("Button " + i);
            btn.setBackground(Color.BLACK);
            this.buttons.add(btn);
            this.getContentPane().add(btn);
        }

        // Setup propagation:
        for (int i = 0; i < n; i++) {
            JButton btn = this.buttons.get(i);

            MouseEventPropagationListener listener = new MouseEventPropagationListener(btn, getNeighbors(i));
            btn.addMouseListener(listener);
        }
    }

    private JButton [] getNeighbors(int i) {
        List<JButton> neighbors = new ArrayList<>();

        if (i > 0) neighbors.add(this.buttons.get(i-1));
        if (i < this.buttons.size() - 1) neighbors.add(this.buttons.get(i + 1));

        return neighbors.toArray(new JButton[0]);
    }

    public static void main(String [] args) {
        EventPropagation ep = new EventPropagation();
        ep.setVisible(true);
    }
}
package scratch.pad.ui;
导入javax.swing.*;
导入java.awt.*;
导入java.awt.event.MouseAdapter;
导入java.awt.event.MouseEvent;
导入java.util.*;
导入java.util.List;
/**
*将事件传播到邻居按钮
*/
公共类EventPropagation扩展了JFrame{
私有列表按钮=新建ArrayList();
私有类MouseEventPropagationListener扩展了MouseAdapter{
//事件源,用于控制事件的传播。
//为了防止无限循环,我们只在
//e.getSource()==此.source;
私有JButton源;
//传播事件的目标。
私有java.util.List目标;
公共MouseEventPropagationListener(JButton源、JButton…目标){
this.source=源;
this.targets=Arrays.asList(目标);
}
@凌驾
公共无效鼠标事件(鼠标事件e){
超级鼠标(e);
//使用this.source,因为e.getSource()可能不同。
此.源.背景(颜色.白色);
调度事件(e);
}
@凌驾
公共无效mouseExited(MouseEvent e){
超级鼠标退出(e);
这个.源.背景(颜色.黑色);
调度事件(e);
}
私有无效调度事件(MouseEvent e){
如果(例如getSource()==源){
for(JButton目标:目标){
目标。调度事件(e);
}
}
}
}
public EventPropagation()抛出HeadlessException{
最终整数n=10;
本文件为setTitle(“事件传播测试”);
此.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
这个.getContentPane().setLayout(新的FlowLayout());
这个。设置大小(300300);
此参数为.setresizeable(false);
//创建按钮
对于(int i=0;i0)个邻居。添加(this.buttons.get(i-1));
如果(i
什么不起作用?您的帖子中是否有任何错误消息或堆栈跟踪?只需使用“事件”对象并更改其状态即可。您甚至不需要(错误地)深入研究数组。为每个按钮分配一个ActionListener,不要共享同一个按钮。@serg.nechaev:不需要这样做——您可以从
getSource()
中获取按下的按钮,他所要做的就是设置该按钮的状态。如果他需要知道i和j值,那么他应该使用一对嵌套for循环来遍历数组,以查看哪个数组项与源匹配。我们可以让他看看,如果他能改进他的问题。。。。啊,好吧。如果你仍然需要帮助,发布一个有效的@alberto,没有必要使用
dispatchEvent(…)
方法,你只需要设置按钮的背景。也就是说,您可以用
target.setBackground(source.getBackground())替换dispatchEvent()语句。您甚至可以在循环之外去掉“if语句”。原始代码的问题在于,您没有确定悬停按钮的逻辑。一旦你认识了邻居,你就可以设置背景。
package scratch.pad.ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.*;
import java.util.List;

/**
 * Propagate event to neighbor buttons
 */
public class EventPropagation extends JFrame {

    private List<JButton> buttons = new ArrayList<>();

    private class MouseEventPropagationListener extends MouseAdapter {

        // The event source, for controlling the propagation of the event.
        // To prevent infinite loop, we only dispatch the event to targets when
        // e.getSource() == this.source;
        private JButton source;

        // Targets to propagate the event.
        private java.util.List<JButton> targets;

        public MouseEventPropagationListener(JButton source, JButton ... targets) {
            this.source = source;
            this.targets = Arrays.asList(targets);
        }

        @Override
        public void mouseEntered(MouseEvent e) {
            super.mouseEntered(e);
            // Use this.source because e.getSource() could be different.
            this.source.setBackground(Color.WHITE);
            dispatchEvent(e);
        }

        @Override
        public void mouseExited(MouseEvent e) {
            super.mouseExited(e);
            this.source.setBackground(Color.BLACK);
            dispatchEvent(e);
        }

        private void dispatchEvent(MouseEvent e) {
            if (e.getSource() == source) {
                for (JButton target : targets) {
                    target.dispatchEvent(e);
                }
            }
        }
    }

    public EventPropagation() throws HeadlessException {

        final int n = 10;

        this.setTitle("Event propagation test");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.getContentPane().setLayout(new FlowLayout());

        this.setSize(300, 300);

        this.setResizable(false);

        // Create the buttons
        for (int i = 0; i < n; i++) {
            JButton btn = new JButton("Button " + i);
            btn.setBackground(Color.BLACK);
            this.buttons.add(btn);
            this.getContentPane().add(btn);
        }

        // Setup propagation:
        for (int i = 0; i < n; i++) {
            JButton btn = this.buttons.get(i);

            MouseEventPropagationListener listener = new MouseEventPropagationListener(btn, getNeighbors(i));
            btn.addMouseListener(listener);
        }
    }

    private JButton [] getNeighbors(int i) {
        List<JButton> neighbors = new ArrayList<>();

        if (i > 0) neighbors.add(this.buttons.get(i-1));
        if (i < this.buttons.size() - 1) neighbors.add(this.buttons.get(i + 1));

        return neighbors.toArray(new JButton[0]);
    }

    public static void main(String [] args) {
        EventPropagation ep = new EventPropagation();
        ep.setVisible(true);
    }
}