2014-02-01 3 views
0

Я собираюсь подключить четыре игры в gridworld, если вы знакомы с этим, но мой учитель абсолютно ничего не сказал нам о щелчках мыши, и подключить четыре части нужно разместить в столбце, в который я нажимаю, но я не могу фигурировать что добавить слушателя мыши, чтобы я сделал Jframe, но я не могу заставить это работать.Как заставить Jframe работать с щелчками мыши?

Так что мне нужно знать, что делать, чтобы заставить щелчок мыши работать, чтобы распечатать координаты x и y щелчка.

public class ConnectFourWorld extends World<Piece> implements MouseListener 
{ 
    private String whosTurn; 
    private boolean gameOver; 
    private String winner; 
    Piece X = new Piece("ex", Color.WHITE, Color.RED); 
    Piece O = new Piece("oh", Color.YELLOW, Color.BLUE); 
    Location column1 = new Location(5, 0); 
    Location column2 = new Location(5, 1); 
    Location column3 = new Location(5, 2); 
    Location column4 = new Location(5, 3); 
    Location column5 = new Location(5, 4); 
    Location column6 = new Location(5, 5); 
    Location column7 = new Location(5, 6); 

    public ConnectFourWorld() 
    { 
    super(new BoundedGrid<Piece>(6,7)); 
    JFrame frame = new JFrame(); 
    frame.setSize(new Dimension(350, 300)); 
    frame.addMouseListener((MouseListener) this); 
    frame.pack(); 
    frame.setVisible(true); 
    winner="no winner"; 
    whosTurn="X"; 
    gameOver=false; 
     setMessage("Welcome to Connect Four World! - - Click a spot - "+whosTurn+"'s      turn.");   
    } 

    public boolean locationClicked(Location loc) 
    { 
     Grid<Piece> grid = getGrid(); 
     if(grid == null) 
     return false; 
    ArrayList<Location> reset = new ArrayList<Location>(); 
    reset = grid.getOccupiedLocations(); 


    if(grid.get(loc)!=null) 
    return false; 

    if(gameOver == true) 
    { 
     for(int i=0; i<reset.size(); i++){ 
      grid.remove(reset.get(i)); 
     } 

    gameOver = false; 
    winner = "no winner"; 
     setMessage("Click a spot - " + whosTurn + "'s turn."); 
    return true; 
    } 
    // Create a new location variable = add a piece 
    Location place = new Location(0,0); 
    place = addPiece(loc); 
    if(place.equals(null)) 
     return false; 
    //if location variable is = to null return false 
    //call the get winner method and step method 
    getWinner(loc); 
    step(); 


    return true; 
    } 

    public Location addPiece(Location loc) 
    { 
    Grid<Piece> grid = getGrid(); 
    if(grid == null) 
    return null; 



int col = loc.getCol(); 
int row = grid.getNumRows() - 1; 
Location spot = new Location(row, col); 
ArrayList<Location> occ = new ArrayList<Location>(); 
boolean taken = false; 
occ = grid.getOccupiedLocations(); 
for (int i=0; i<occ.size(); i++){ 
    if(spot.equals(occ.get(i))) 
     taken=true; 
} 
//loop that runs as long as location is valid and location is not null 
    // move up in the row and add the new Location to that row and col 
while((!spot.equals(null))&&taken==false){ 
    for (int i=0; i<occ.size(); i++){ 
     if(spot.equals(occ.get(i))) 
      taken=true; 
    } 
    row++; 
} 
//add a piece to that location and return the location 
if(whosTurn.equals("X")) 
    grid.put(spot, X); 
else if(whosTurn.equals("O")) 
    grid.put(spot, O); 
return spot; 
    } 

    //This method is done 
public void step() 
    { 
    Grid<Piece> grid = getGrid(); 
    if (grid == null) 
     return; 
     if(!winner.equals("no winner")) 
     { 
      setMessage("And the winner is..... " + winner + "\n Click anywhere on board to play again."); 
       gameOver = true; 

    } 
} 

    //This one is done 
    public boolean isWorldFull() 
    { 
    Grid<Piece> grid = getGrid(); 
     if(grid == null) 
     return false; 

    ArrayList <Location> list = grid.getOccupiedLocations(); 
    return (grid.getNumCols() * grid.getNumRows() == list.size()); 
    } 


    public void resetWorld() 
    { 

    } 

    public String getWinner(Location loc) 
    { 
    return ""; 
    } 
@Override 
public void mouseClicked(MouseEvent e) { 
    int x=e.getX(); 
     int y=e.getY(); 
    System.out.println(x+","+y); 
... 

У меня есть отдельный главный класс, который собирается запустить этот

+0

Вы уже давно задали этот вопрос. – BitNinja

+1

Простой [** Минимальный, полный, проверенный и читаемый пример **] (http://stackoverflow.com/help/mcve) хватило бы. –

+0

Ваш пример показывает рамку с прикрепленным к ней MouseListerner, но, похоже, это не то место, где ваша игра действительно привязана. Что такое мир? – MadProgrammer

ответ

0

Добавить слушателю MOUSE

 addMouseListener(new MouseListener() { 

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

     } 

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

     } 

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

     } 

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

     } 

     @Override 
     public void mouseClicked(MouseEvent arg0) { 
      System.out.println(arg0.getLocationOnScreen().x); 
      System.out.println(arg0.getLocationOnScreen().y); 
     } 
    }); 
+0

, я попытался сделать это таким образом, но я получаю ошибки в добавлении «EnumBody» в этой последней строке. – user3255621

+0

Я не знаю, что делать, из-за этой ошибки – user3255621

+0

Не только эта ошибка, но и щелчки мыши по-прежнему не работают. – user3255621

0

Вы должны Перезапишите GridWorld GUIController Class..inside конструктор их является метод вызываемый display.addMouseListener(). В значительной степени просто напишите свой код. Я верю, что они хранят местоположение, которое вы нажали в переменной loc. Довольно легко, как только вы это знаете. Чтобы получить объект, просто выполните parentFrame.getWorld(). GetGrid(). Get (loc) ... довольно прямо вперед ... надеюсь, что это поможет!

Смежные вопросы