首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用于Java的用户鼠标单击对象

用于Java的用户鼠标单击对象
EN

Stack Overflow用户
提问于 2018-10-24 07:24:25
回答 1查看 1K关注 0票数 1

我正在尝试制作的地图遇到了问题。我正在尝试做的是为我的校园中的一栋建筑制作一张楼层的网格地图。整个楼层是一个正方形,走廊上有不同的房间。我正在为一个房间里的人制作地图。现在,我“硬编码”的是正方形的坐标(JPanel),我想用它来表示有人在里面。我使用JPanel网格将正方形存储到行和列中。我想知道的是如何检测鼠标点击其中一个JPanel对象,而不仅仅是框架的x和y坐标。

此外,据我所知,我知道我的代码绝对可以改进,所以如果有更好的方法来做到这一点,请随时告诉我。

谢谢。

import javax.swing.*;



import java.util.*;
import java.util.List;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;


public class Example extends JPanel {

    enum Token {VIDE, CERCLE_BLEU, CERCLE_ROUGE}

    private static final int ICON_W = 35;

    private JPanel[][] grid;




    Example(int rows, int cols) {

        setLayout(new GridLayout(rows, cols, 1, 1));
        setBorder(BorderFactory.createLineBorder(Color.red));
        setBackground(Color.BLACK);


        createGrid(rows, cols);

        Click click = new Click();
        this.addMouseListener(click);


    }



    void createGrid(int rows, int cols) {
        boolean personTrapped = false;
        grid = new JPanel[rows][cols];
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                grid[r][c] = new JPanel();
                grid[r][c].setOpaque(true);
                grid[r][c].setBackground(Color.WHITE);
                grid[r][c].setPreferredSize(new Dimension(ICON_W, ICON_W));
                add(grid[r][c]);

            }
        }
        /*
         * Path for floor in building
         */
        grid[1][1].setBackground(Color.DARK_GRAY);
        grid[1][2].setBackground(Color.DARK_GRAY);
        grid[1][3].setBackground(Color.DARK_GRAY);
        grid[1][4].setBackground(Color.DARK_GRAY);
        grid[1][5].setBackground(Color.DARK_GRAY);
        grid[1][6].setBackground(Color.DARK_GRAY);
        grid[1][7].setBackground(Color.DARK_GRAY);
        grid[1][8].setBackground(Color.DARK_GRAY);

        grid[2][1].setBackground(Color.DARK_GRAY);
        grid[3][1].setBackground(Color.DARK_GRAY);
        grid[4][1].setBackground(Color.DARK_GRAY);
        grid[5][1].setBackground(Color.DARK_GRAY);
        grid[6][1].setBackground(Color.DARK_GRAY);
        grid[7][1].setBackground(Color.DARK_GRAY);
        grid[8][1].setBackground(Color.DARK_GRAY);

        grid[2][8].setBackground(Color.DARK_GRAY);
        grid[3][8].setBackground(Color.DARK_GRAY);
        grid[4][8].setBackground(Color.DARK_GRAY);
        grid[5][8].setBackground(Color.DARK_GRAY);
        grid[6][8].setBackground(Color.DARK_GRAY);
        grid[7][8].setBackground(Color.DARK_GRAY);
        grid[8][8].setBackground(Color.DARK_GRAY);

        grid[8][1].setBackground(Color.DARK_GRAY);
        grid[8][2].setBackground(Color.DARK_GRAY);
        grid[8][3].setBackground(Color.DARK_GRAY);
        grid[8][4].setBackground(Color.DARK_GRAY);
        grid[8][5].setBackground(Color.DARK_GRAY);
        grid[8][6].setBackground(Color.DARK_GRAY);
        grid[8][7].setBackground(Color.DARK_GRAY);

        // Rooms in building
        grid[0][3].setBackground(Color.DARK_GRAY);
        grid[2][4].setBackground(Color.DARK_GRAY);
        grid[0][6].setBackground(Color.DARK_GRAY);
        grid[3][9].setBackground(Color.DARK_GRAY);
        grid[5][7].setBackground(Color.DARK_GRAY);
        grid[7][9].setBackground(Color.DARK_GRAY);
        grid[9][7].setBackground(Color.DARK_GRAY);
        grid[7][5].setBackground(Color.DARK_GRAY);
        grid[9][3].setBackground(Color.DARK_GRAY);
        grid[7][0].setBackground(Color.DARK_GRAY);
        grid[5][2].setBackground(Color.DARK_GRAY);
        grid[3][0].setBackground(Color.DARK_GRAY);


    }




    public static void main(String[] args) 
    {
        SwingUtilities.invokeLater(new Runnable() 
        {

            @Override
            public void run() 
            {
                JFrame frame = new JFrame("RIC Emergency Map");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                Example example = new Example(15, 10);
                frame.add(example);

                frame.addWindowListener(new WindowAdapter() 
                {
                    public void windowClosing(WindowEvent we) 
                    {

                        int result = JOptionPane.showConfirmDialog(frame, "Do you want to Exit ?", "Exit Confirmation : ",JOptionPane.YES_NO_OPTION);
                        if (result == JOptionPane.YES_OPTION)
                          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        else if (result == JOptionPane.NO_OPTION)
                          frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
                    }

                });

                frame.getGlassPane().setVisible(true);
                frame.setLocationRelativeTo(null);
                frame.pack();
                //frame.setSize(500, 500);
                frame.setResizable(true);
                frame.setVisible(true);
            }
        });
    }
}



class Move implements MouseMotionListener
{

    @Override
    public void mouseDragged(MouseEvent arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseMoved(MouseEvent e) {
        // TODO Auto-generated method stub

    }

}

class Click implements MouseListener
{
    @Override
    public void mouseClicked(MouseEvent e) {
        // TODO Auto-generated method stub
        System.out.println(e.getPoint());
        if (e.getX() >= 150 && e.getX() <= 185 && e.getY() >= 73 && e.getY() <= 108)
        {
            System.out.println("There is somebody in this room!!!");
        }
        else
        {
            System.out.println("Oh no, there isn't anyone in this room. Hurry! Keep looking!");
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseExited(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mousePressed(MouseEvent e) {
        // TODO Auto-generated method stub

    }

    @Override
    public void mouseReleased(MouseEvent e) {
        // TODO Auto-generated method stub

    }


}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-24 07:50:41

只需创建一个MouseListener (或更好的MouseAdapter),并在创建网格时将其添加到JPanel网格中的每个JPanel单元格中。

例如,如果您有一个名为MyMouse的MouseAdapter:

grid = new JPanel[rows][cols];
MyMouse myMouse = new MyMouse();
for (int r = 0; r < grid.length; r++) {
    for (int c = 0; c < grid[r].length; c++) {
        grid[r][c] = new JPanel();
        grid[r][c].setOpaque(true);
        Color color = data[r][c] == 0 ? Color.WHITE : Color.DARK_GRAY;
        grid[r][c].setBackground(color);
        grid[r][c].setPreferredSize(new Dimension(ICON_W, ICON_W));
        grid[r][c].addMouseListener(myMouse); // ***** here, add the listener)
        add(grid[r][c]);

    }
}

将会起作用:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class Example2 extends JPanel {
    // enum Token {
    //     VIDE, CERCLE_BLEU, CERCLE_ROUGE
    // }
    private static final int ICON_W = 35;
    private JPanel[][] grid;

    public Example2(int[][] data) {
        int rows = data.length;
        int cols = data[0].length;

        setLayout(new GridLayout(rows, cols, 1, 1));
        setBorder(BorderFactory.createLineBorder(Color.red));
        setBackground(Color.BLACK);

        createGrid(data);
    }

    private void createGrid(int[][] data) {
        int rows = data.length;
        int cols = data[0].length;
        grid = new JPanel[rows][cols];
        MyMouse myMouse = new MyMouse();
        for (int r = 0; r < grid.length; r++) {
            for (int c = 0; c < grid[r].length; c++) {
                grid[r][c] = new JPanel();
                grid[r][c].setOpaque(true);
                Color color = data[r][c] == 0 ? Color.WHITE : Color.DARK_GRAY;
                grid[r][c].setBackground(color);
                grid[r][c].setPreferredSize(new Dimension(ICON_W, ICON_W));
                grid[r][c].addMouseListener(myMouse);
                add(grid[r][c]);

            }
        }
    }

    private class MyMouse extends MouseAdapter {
        @Override
        public void mousePressed(MouseEvent e) {
            JPanel source = (JPanel) e.getSource();
            int r = -1;
            int c = -1;
            for (int row = 0; row < grid.length; row++) {
                for (int col = 0; col < grid[row].length; col++) {
                    if (grid[row][col] == source) {
                        r = row;
                        c = col;
                        break;
                    }
                }
            }
            Color color = source.getBackground();

            System.out.printf("Cell: [%d, %d] color white: %b%n", c, r, color.equals(Color.WHITE));
        }
    }

    private static void createAndShowGui() {
        int[][] data = {
                {0, 0, 0, 1, 0, 0, 1, 0, 0, 0},
                {0, 1, 1, 1, 1, 1, 1, 1, 1, 0},
                {0, 1, 0, 0, 1, 0, 0, 0, 1, 0},
                {1, 1, 0, 0, 0, 0, 0, 0, 1, 1},
                {0, 1, 0, 0, 0, 0, 0, 0, 1, 0},
                {0, 1, 1, 0, 0, 0, 0, 1, 1, 0},
                {0, 1, 0, 0, 0, 0, 0, 0, 1, 0},
                {1, 1, 0, 0, 0, 1, 0, 0, 1, 1},
                {0, 1, 1, 1, 1, 1, 1, 1, 1, 0},
                {0, 0, 0, 1, 0, 0, 1, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
                {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
        };
        Example2 mainPanel = new Example2(data);

        JFrame frame = new JFrame("RIC Emergency Map");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}

在本例中,我通过MouseEvent的.getSource()方法获取JPanel单元格。然后,我遍历网格以找到单元格的坐标。我还可以提取它的背景颜色,看看它是否是白色的。

private class MyMouse extends MouseAdapter {
    @Override
    public void mousePressed(MouseEvent e) {
        JPanel source = (JPanel) e.getSource();

        // initially set row and column to -1
        int r = -1;
        int c = -1;

        // iterate through the grid finding out which cell is source
        for (int row = 0; row < grid.length; row++) {
            for (int col = 0; col < grid[row].length; col++) {
                if (grid[row][col] == source) {
                    r = row;
                    c = col;
                    break;
                }
            }
        }
        Color color = source.getBackground();

        System.out.printf("Cell: [%d, %d] color white: %b%n", c, r, color.equals(Color.WHITE));
    }
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52959070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档