Java(JFrames):mouseListener()仅在ArrayList

时间:2016-04-07 02:40:06

标签: java swing jframe jpanel mouselistener

我正在尝试制作一个简单的棋子游戏,但是当我运行当前版本打印10个随机颜色(白色或黑色)的方格时,Block类的mouseListener只响应最后2个块而不是任何其他街区。我完全不知道为什么这只适用于2个街区。 JFrame的代码在MyCraft.java中,框架上的实际面板的代码在MyCraftPanel中,Block实例的代码在Block.java中

如果有人能够回复他们的反馈,将非常感谢!

MyCraft.java的代码:

package com.matthewpipie.MyCraft;

import javax.swing.JFrame;

public class MyCraft {

    public static void main(String[] args) {
        final int FRAME_WIDTH = 1280;
        final int FRAME_HEIGHT = 720;

        JFrame frame = new JFrame("MyCraft");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new MyCraftPanel());
        frame.setSize(FRAME_WIDTH, FRAME_HEIGHT);
        frame.setVisible(true);
    }

}

MyCraftPanel.java的代码:http://pastebin.com/9bQDh2Hm

Block.java的代码:http://pastebin.com/J41DFbF7

我发布了pastebin,因为我认为它会占用太多空间。

谢谢!

编辑:由于请求,这里是重要代码"来自Blocks.java:

package com.matthewpipie.MyCraft;

public class Block extends JPanel {
    private static final int BLOCK_SIZE = 90;
    private int id;
    private int x;
    private int y;
    private Color color;

    public Block(int id, int x, int y) {
        this.setUpFrame();
        this.id = id;
        this.x = x;
        this.y = y;
        this.generateColor();
        this.setActionListeners();
    }

    public void setUpFrame() {
        this.setPreferredSize(new Dimension(Block.getBLOCK_SIZE(), Block.getBLOCK_SIZE()));
    }

    public void setActionListeners() {
        System.out.print("setting up ");
        System.out.println(this.getId());
        this.addMouseListener(new MouseAdapter() {
            public void mouseReleased(MouseEvent e) {
                System.out.println("clicky45");
            }
        });
    }

    **getters and setters*
}

" clicky45"只有当我点击某个奇怪的垂直不可见线的某个地方时才会出现。

编辑:我发现它与块的大小有关。它们越大,可以点击的越多。如果它们足够小,则无法单击它们。

0 个答案:

没有答案