很奇怪的Mouse Listener和If语句

时间:2013-04-08 01:52:01

标签: java eclipse swing if-statement mouseevent

在你读到这篇文章之前,我只是想说,任何帮助对我来说都非常有帮助。我非常绝望。我花了至少一个星期试图在Eclipse中完成这项工作,我想我错过了一些明显的东西,我真的需要你的帮助。

现在我的鼠标监听器包含每个房间的if语句'并且在那些if语句中有一个双重for循环,它告诉JFrame是否在JFrame的某个区域内单击了鼠标以重新绘制相应的房间'。

现在让我们说#4室可以导致#5或#6。来自#4> #6显示没有问题。现在来自#5> #4有问题。出于某种原因,#4房间的事件区域显示在#5(它不应该),所以现在我可以在点击之前的事件区域时转到#4或#6。

我已经在其他房间试过了这个'这个问题并没有出现在他们身上。我已经得出结论,在与多条路径相连的房间之间往返前进可能需要做些什么。我已经附加了一个视觉通道和孤立的代码,以使事情更容易(数字只是房间#')。

MouseAdapter mouseHandler = new MouseAdapter()
      {
          public void mouseClicked(MouseEvent e)
          {
             //System.out.println(e.getPoint());
            if(n==6)//R6
             {
                for(int i = 116;i<132;i++)//3a
              {
                  if(e.getX() == i)
                  {
                      for(int j = 388;j<404;j++)
                      {
                          if(e.getY() == j)
                          {
                            n = 7;//3b
                              return;
                          }
                      }
                  }
              }
                 for(int i = 116;i<132;i++)//2b
                  {
                      if(e.getX() == i)
                      {
                          for(int j = 308;j<324;j++)
                          {
                              if(e.getY() == j)
                              {
                                 n = 4;//2a
                                  return;
                              }
                          }
                      }
                  }
                 for(int i = 580;i<596;i++)//8a
              {
                  if(e.getX() == i)
                  {
                      for(int j = 372;j<388;j++)
                      {
                          if(e.getY() == j)
                          {
                             n = 2;//8b
                              return;
                          }
                      }
                  }
              }
             }
            if(n==5)//R5
             {
                 for(int i = 220;i<268;i++)//1b
                  {
                      if(e.getX() == i)
                      {
                          for(int j = 437;j<485;j++)
                          {
                              if(e.getY() == j)
                              {
                                  n = 4;//1a
                                  return;
                              }
                          }
                      }
                  }
             }
            if(n==4)//R4
             {
                 for(int i = 179;i<244;i++)//2a
                  {
                      if(e.getX() == i)
                      {
                          for(int j = 403;j<468;j++)
                          {
                              if(e.getY() == j)
                              {
                                 n = 6;//2b
                                  return;
                              }
                          }
                      }
                  }
                 for(int i = 436;i<500;i++)//1a
                      {
                          if(e.getX() == i)
                          {
                              for(int j = 403;j<468;j++)
                              {
                                  if(e.getY() == j)
                                  {
                                     n = 5;//1b
                                      return;
                                  }
                              }
                          }
                      }
                 for(int i = 274;i<406;i++)//A2
                  {
                      if(e.getX() == i)
                      {
                          for(int j = 193;j<276;j++)
                          {
                              if(e.getY() == j)
                              {
                                  n = 0;//A1
                                  return;
                              }
                          }
                      }
                  }
             }
            if(n==0)//R0
             {
                 for(int i = 459;i<493;i++)//A1
              {
                  if(e.getX() == i)
                  {
                      for(int j = 110;j<133;j++)
                      {
                          if(e.getY() == j)
                          {
                              n = 4;//A2
                              return;
                          }
                      }
                  }
              }
             }
            repaint();
             //http://stackoverflow.com/questions/5654208/making-a-jbutton-invisible-but-clickable
          }
          public void mouseMoved(MouseEvent e)
          {
              // = e.getPoint();
              //repaint();
          }
      };

      addMouseMotionListener(mouseHandler);
      addMouseListener(mouseHandler);

enter image description here

2 个答案:

答案 0 :(得分:4)

这旨在演示Rectangle的使用以及Room的自包含概念。

每个Room可以有1个或更多存在,每个出口通向另一个房间。这本质上是一种链表。

每个位置的Rectangle是动态计算的,更易于渲染和控制。这个例子基本上只显示活动房间和连接房间。每次你点击一个房间,那个房间就会变成活动房间(在中间)并呈现它的链接存在。

enter image description here

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Rooms {

    public static void main(String[] args) {
        new Rooms();
    }

    public Rooms() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new RoomsPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class RoomsPane extends JPanel {

        private Room currentRoom;

        public RoomsPane() {

            currentRoom = new Room("0", new Dimension(100, 100), null, null);
            currentRoom.addExit(ExitPoint.East, createRoom(1, currentRoom, ExitPoint.West));

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    if (getBounds(currentRoom).contains(e.getPoint())) {
                        // current room
                    } else {
                        for (Room room : currentRoom.getRooms()) {
                            if (getBounds(room).contains(e.getPoint())) {
                                currentRoom = room;
                                repaint();
                                break;
                            }
                        }
                    }
                }
            });

        }

        protected boolean chance() {
            return Math.round(Math.random() * 1) == 0 ? false : true;
        }

        public Room createRoom(int count, Room parent, ExitPoint entryPoint) {
            int width = (int) Math.round(Math.random() * 90) + 10;
            int height = (int) Math.round(Math.random() * 90) + 10;
            Room room = new Room(String.valueOf(count), new Dimension(width, height), parent, entryPoint);
            if (count < 10) {
                count++;

                if (chance() && !room.hasExit(ExitPoint.North)) {
                    room.addExit(ExitPoint.North, createRoom(count, room, ExitPoint.South));
                }
                if (chance() && !room.hasExit(ExitPoint.East)) {
                    room.addExit(ExitPoint.East, createRoom(count, room, ExitPoint.West));
                }
                if (chance() && !room.hasExit(ExitPoint.South)) {
                    room.addExit(ExitPoint.South, createRoom(count, room, ExitPoint.North));
                }
                if (chance() && !room.hasExit(ExitPoint.West)) {
                    room.addExit(ExitPoint.West, createRoom(count, room, ExitPoint.West));
                }

            }
            return room;
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

        public Rectangle getBounds(Room room) {

            Rectangle bounds = null;
            // Can't get the bounds for a room not linked to current room
            if (currentRoom.isLinkedTo(room) || currentRoom == room) {
                Dimension size = currentRoom.getSize();
                int width = getWidth() - 1;
                int height = getHeight() - 1;
                int x = (width - size.width) / 2;
                int y = (height - size.height) / 2;
                if (currentRoom != room) {

                    switch (currentRoom.getExit(room)) {
                        case North:
                            y -= room.getSize().height;
                            x = (width - room.getSize().width) / 2;
                            break;
                        case South:
                            y += size.height;
                            x = (width - room.getSize().width) / 2;
                            break;
                        case East:
                            x += size.width;
                            y = (height - room.getSize().height) / 2;
                            break;
                        case West:
                            x -= room.getSize().width;
                            y = (height - room.getSize().height) / 2;
                            break;
                    }

                    size = room.getSize();

                }
                bounds = new Rectangle(x, y, size.width, size.height);
            }
            return bounds;

        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();

            FontMetrics fm = g2d.getFontMetrics();

            g2d.setColor(Color.GRAY);
            for (Room room : currentRoom.getRooms()) {
                Rectangle bounds = getBounds(room);
                g2d.draw(bounds);
                g2d.drawString(
                        room.getName(),
                        bounds.x + ((bounds.width - fm.stringWidth(room.getName())) / 2),
                        bounds.y + ((bounds.height - fm.getHeight()) / 2) + fm.getAscent());
            }

            Rectangle bounds = getBounds(currentRoom);
            g2d.setColor(Color.BLUE);
            g2d.draw(bounds);
            g2d.drawString(
                    currentRoom.getName(),
                    bounds.x + ((bounds.width - fm.stringWidth(currentRoom.getName())) / 2),
                    bounds.y + ((bounds.height - fm.getHeight()) / 2) + fm.getAscent());

            g2d.dispose();
        }
    }

    public enum ExitPoint {

        North,
        South,
        East,
        West
    }

    public class Room {

        private Dimension size;
        private Map<ExitPoint, Room> exists;
        private String name;

        public Room(String name, Dimension dim, Room parent, ExitPoint entryPoint) {
            size = new Dimension(dim);
            exists = new HashMap<>(4);
            this.name = name;
            if (parent != null) {
                addExit(entryPoint, parent);
            }
        }

        public String getName() {
            return name;
        }

        public Dimension getSize() {
            return size;
        }

        public void addExit(ExitPoint point, Room room) {
            exists.put(point, room);
        }

        public boolean isLinkedTo(Room room) {
            return exists.values().contains(room);
        }

        public Room[] getRooms() {
            return exists.values().toArray(new Room[exists.size()]);
        }

        public boolean hasExit(ExitPoint ep) {
            return exists.containsKey(ep);
        }

        public ExitPoint getExit(Room room) {
            ExitPoint ep = null;
            for (ExitPoint exit : exists.keySet()) {
                if (exists.get(exit) == room) {
                    ep = exit;
                    break;
                }
            }
            return ep;
        }
    }
}

答案 1 :(得分:3)

您似乎正在尝试查看鼠标是否已在区域内单击,并且您似乎正在尝试使用嵌套for循环执行此操作。不要为此目的使用for循环。而是使用if块。最简单的方法是创建矩形并查看鼠标是否已使用其contains(Point p)方法在其中单击。