Results 1 to 13 of 13
  1. #1
    Danieldcc is offline Member
    Join Date
    Sep 2010
    Posts
    83
    Rep Power
    0

    Default Mouse Listener and JButtons

    So, my code works and finds the right position on the panel but when i put a JButton over the panel, it doesn't work anymore. Why can I use getX and getY if I don't put the jbutton on top but once i put the jbutton on top it doesn't find the getX and getY anymore? I want to have it done so that when you press the jbutton, it finds the coordinates of the array and finds what number is stored at those cordinates. If it >= to 0 then the Jbutton disappears...help please.....

    Java Code:
    public MineSweeperGUI()
        {
         logic.startNewGame(10, 10);
         this.setLayout(new GridLayout(10,10));
         this.setPreferredSize(new Dimension(400, 400));
         this.addMouseListener(new MyMouseListener());
         
         for(int i = 0; i < ROWS; i++) {
            for(int j = 0; j < COLUMNS; j++) {
                cell = new JPanel();
                cell.setLayout(new BorderLayout());
                cell.setBorder(BorderFactory.createLineBorder(Color.RED));
                number = new JLabel(Integer.toString(logic.getValue(i, j)), 0);
                cell.add(number);
               
                //if(x != i && y != j)
                //{
                    cover = new JButton();
                     cell.add(cover);
    
                //}
                this.add(cell);              
                
            }}
         
        }
        class MyMouseListener implements MouseListener
    {
    public void mousePressed(MouseEvent event)
    {
    x = event.getX();
    System.out.println(x + "is x");
    x = x / 40;
    y = event.getY(); 
    System.out.println(y + "is y");
    y = y / 40;

  2. #2
    eRaaaa is offline Senior Member
    Join Date
    Oct 2010
    Location
    Germany
    Posts
    787
    Rep Power
    5

    Default Re: Mouse Listener and JButtons

    Because "this" has probably not the focus and thus the listener is not responding.
    Another solution/proposal would be, to set an action command for each button (setActionCommand(...)) with the x and y coordinate and add a actionlistener to each button (could be the same listener!) instead of a mouselistener!!!
    a possible example
    Java Code:
    	public static void main(String[] args) throws Exception {
    		JFrame frame = new JFrame();
    		JPanel panel = new JPanel(new GridLayout(10,10));
    		ActionListener listener = new ActionListener() {
    			@Override
    			public void actionPerformed(ActionEvent e) {
    				System.out.println(e.getActionCommand());
    			}
    		};
    		for (int i = 0; i < 10*10; i++) {
    			JButton btn = new JButton(i+"");
    			btn.addActionListener(listener);
    			btn.setActionCommand(i/10+"=y"+" "+i%10+"=x"); //example
    			panel.add(btn);
    		}
    		frame.add(panel);
    		frame.pack();
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true);
    	}

  3. #3
    Danieldcc is offline Member
    Join Date
    Sep 2010
    Posts
    83
    Rep Power
    0

    Default Re: Mouse Listener and JButtons

    tks for the help......I will try your solution, but how do i get my solution to work? I tried removing this but to no avail. If I click on the border it works as it's part of the jpanel but the buttons don't respond or give getX and getY coordinates of 0 all the time

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is online now Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,234
    Rep Power
    19

    Default Re: Mouse Listener and JButtons

    Don't use a MouseListener for JButtons, use an ActionListener.

    Moving this thread to the correct forum.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  5. #5
    Danieldcc is offline Member
    Join Date
    Sep 2010
    Posts
    83
    Rep Power
    0

    Default Re: Mouse Listener and JButtons

    Ok. yeah, that's what I was thinking. I'm gona try after work when I get home. Tks. Also, I'm gona paint on top of the JButton eventually to mark the mines. In that case, still use actionListener?

  6. #6
    dheaven is offline Member
    Join Date
    Oct 2011
    Posts
    15
    Rep Power
    0

    Default Re: Mouse Listener and JButtons

    Quote Originally Posted by Danieldcc View Post
    Ok. yeah, that's what I was thinking. I'm gona try after work when I get home. Tks. Also, I'm gona paint on top of the JButton eventually to mark the mines. In that case, still use actionListener?
    If you're trying to create a Minesweeper game, you might wanna check this out:
    Dystopian Code: Minesweeper Clone in Java AWT

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is online now Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,234
    Rep Power
    19

    Default Re: Mouse Listener and JButtons

    AWT's dated. Use Swing. Or if you really want to be up to date, learn and use JavaFX 2.0.

    I'm gona paint on top of the JButton eventually to mark the mines.
    Before you end up spending half of the rest of your life reinventing existing wheels, go through some tutorials.
    Trail: Creating a GUI With JFC/Swing (The Java™ Tutorials)
    How to Use Buttons, Check Boxes, and Radio Buttons (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)
    How to Use Icons (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components)

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  8. #8
    Danieldcc is offline Member
    Join Date
    Sep 2010
    Posts
    83
    Rep Power
    0

    Default Re: Mouse Listener and JButtons

    Ok. had some time to get back at this.....OK. I butchered the code again. I got to the point where JButton is pressed I can identify which one and set the corresponding value of 2d array to 1 to indicate that was pressed and should not get drawn anymore. Now, my problem is I need to repaint and if 2d array value set to 1, then no jbutton drawn in that location, but the jlabel needs to show from underneath that has the number of bombs. How do I re-draw this component now? I have no paintmethod. Help please

    Java Code:
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.border.*;
    
    public class MineSweeperGUI extends JPanel
    {
    private final int ROWS = 10;
    private final int COLUMNS = 10;
    private JPanel cell;
    
    private JLabel number;
    MineSweeperLogic logic = new MineSweeperLogic();
    // ActionListener listener = new MyMouseListener();
    
    public MineSweeperGUI()
        {
           logic.startNewGame(10, 10);
           setLayout(new GridLayout(10,10));
           setPreferredSize(new Dimension(400, 400));
            
          
         for(int i = 0; i < ROWS; i++) {
            for(int j = 0; j < COLUMNS; j++) {
                cell = new JPanel();
                cell.setLayout(new BorderLayout());
                cell.setBorder(BorderFactory.createLineBorder(Color.RED));
                number = new JLabel(Integer.toString(logic.getValue(i, j)), 0);
                
                
                if(logic.setvalue(i, j) == 0) {    // initial value of 2d array set to 0 so that all jbuttons are added
                    final JButton cover = new JButton();
                    cover.setActionCommand(i + "" + j);
                    System.out.println(cover.getActionCommand());
                    cell.add(number);
                     cell.add(cover);
                    
    class MyMouseListener implements ActionListener
    {
    public void actionPerformed(ActionEvent event)
    {
    int cx = Integer.parseInt(cover.getActionCommand())/10;
    int cy = Integer.parseInt(cover.getActionCommand())%10;
    logic.setvalue2(cx, cy);  // sets the value of 2d array to 1 so it doesn't get drawn
    }
         
         }
                cover.addActionListener(new MyMouseListener());
                        }               
                add(cell);             
            
            }}
          
        }
        
    
                
                
       
    
    
    public static void main(String[] args)
        {
            
            JFrame frame = new JFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setLayout(new FlowLayout()); //prevents resizing the jpanels
            frame.add(new MineSweeperGUI());
            frame.pack();
            frame.setVisible(true);
        }
    }
    and this is the logic part I have so far....

    Java Code:
    import java.util.Random;
    
    public class MineSweeperLogic
    {
        int[][] newGame, testing;
    
    public void startNewGame(int width, int height)
        {
            int rows = width;
            int columns = height;
            newGame = new int[width][height];
            testing = new int[10][10];	
            Random generator = new Random();
            int percentageOfMines = 10; //10% of area to be mines
            int mines = (width * height) / percentageOfMines;
            int bomb = -1;
            for (int i = 0; i < rows; i++) {
              for (int j = 0; j < columns; j++) {
                  newGame[i][j] = 0;
                  testing[i][j] = 0;
                }}
            int count = mines;
            while (count > 0)
            {
                int x = generator.nextInt(rows);
                int y = generator.nextInt(columns);
                
                if(newGame[x][y] != bomb)
                {
                    newGame[x][y] = bomb;
                    count--;
                        if(x == 0 && y == 0)
                        {
                            if(newGame[x + 1][y] != bomb) newGame[x + 1][y]++;
                            if(newGame[x][y + 1] != bomb) newGame[x][y + 1]++;
                            if(newGame[x + 1][y + 1] != bomb) newGame[x + 1][y + 1]++;
                        }
                        else if(x == (rows - 1) && y == 0)
                        {
                            if(newGame[x - 1][y] != bomb) newGame[x - 1][y]++;
                            if(newGame[x][y + 1] != bomb) newGame[x][y + 1]++;
                            if(newGame[x - 1][y + 1] != bomb) newGame[x - 1][y + 1]++;
                        }
                        else if(x == 0 && y == (columns - 1))
                        {
                            if(newGame[x][y - 1] != bomb) newGame[x][y - 1]++;
                            if(newGame[x + 1][y] != bomb) newGame[x + 1][y]++;
                            if(newGame[x + 1][y - 1] != bomb) newGame[x + 1][y - 1]++;
                        }
                        else if(x == (rows - 1) && y == (columns - 1))
                        {
                            if(newGame[x - 1][y] != bomb) newGame[x - 1][y]++; 
                            if(newGame[x][y - 1] != bomb) newGame[x][y - 1]++;
                            if(newGame[x - 1][y - 1] != bomb) newGame[x - 1][y - 1]++;
                        }
                        else if(x == 0)
                        {
                            if(newGame[x + 1][y] != bomb) newGame[x + 1][y]++;
                            if(newGame[x][y - 1] != bomb) newGame[x][y - 1]++;
                            if(newGame[x][y + 1] != bomb) newGame[x][y + 1]++;
                            if(newGame[x + 1][y - 1] != bomb) newGame[x + 1][y - 1]++;
                            if(newGame[x + 1][y + 1] != bomb) newGame[x + 1][y + 1]++;
                            
                        }
                        else if(x == (rows - 1))
                        {
                            if(newGame[x - 1][y] != bomb) newGame[x - 1][y]++;
                            if(newGame[x][y - 1] != bomb) newGame[x][y - 1]++;
                            if(newGame[x][y + 1] != bomb) newGame[x][y + 1]++;
                            if(newGame[x - 1][y - 1] != bomb) newGame[x - 1][y - 1]++;
                            if(newGame[x - 1][y + 1] != bomb) newGame[x - 1][y + 1]++;
                        }
                        else if(y == 0)
                        {
                            if(newGame[x][y + 1] != bomb) newGame[x][y + 1]++;
                            if(newGame[x - 1][y] != bomb) newGame[x - 1][y]++;
                            if(newGame[x + 1][y] != bomb) newGame[x + 1][y]++;
                            if(newGame[x - 1][y + 1] != bomb) newGame[x - 1][y + 1]++;
                            if(newGame[x + 1][y + 1] != bomb) newGame[x + 1][y + 1]++;
                        }
                        else if(y == (columns - 1))
                        {
                            if(newGame[x][y - 1] != bomb) newGame[x][y - 1]++;
                            if(newGame[x - 1][y] != bomb) newGame[x - 1][y]++;
                            if(newGame[x + 1][y] != bomb) newGame[x + 1][y]++;
                            if(newGame[x - 1][y - 1] != bomb) newGame[x - 1][y - 1]++;
                            if(newGame[x + 1][y - 1] != bomb) newGame[x + 1][y - 1]++;
                        }
                        else
                        {
                            if(newGame[x][y + 1] != bomb) newGame[x][y + 1]++;
                            if(newGame[x][y - 1] != bomb) newGame[x][y - 1]++;
                            if(newGame[x - 1][y] != bomb) newGame[x - 1][y]++;
                            if(newGame[x + 1][y] != bomb) newGame[x + 1][y]++;
                            if(newGame[x + 1][y + 1] != bomb) newGame[x + 1][y + 1]++;
                            if(newGame[x - 1][y - 1] != bomb) newGame[x - 1][y - 1]++;
                            if(newGame[x - 1][y + 1] != bomb) newGame[x - 1][y + 1]++;
                            if(newGame[x + 1][y - 1] != bomb) newGame[x + 1][y - 1]++;
                        }
                }
            }
        }
    int getValue(int x, int y)
        {
            return newGame[x][y];
        }
        int getValue2(int x, int y)
        {
            return testing[x][y];
        }
        int setvalue(int x, int y)
        {
                  
                 
                return testing[x][y];
            
        }
        void setvalue2(int x, int y)
        {
            testing[x][y] = 1;
        }
    
        
    
            
                
            
         /*       for (int i = 0; i < width; i++) {
              for (int j = 0; j < height; j++) {
                  System.out.print(newGame[i][j]);
                }
            System.out.println(); } */ 
            
        }
    I'm pretty set on doing it with jbuttons, but suggestions are always welcome in improving/making the code better. I'm stuck here for a while now so PLEASE PLEASE lend some assistance

  9. #9
    Danieldcc is offline Member
    Join Date
    Sep 2010
    Posts
    83
    Rep Power
    0

    Default Re: Mouse Listener and JButtons

    Modified a little and trying to use the remove() method, but still not showing me the jlabel component.

    Java Code:
    for(int i = 0; i < ROWS; i++) {
            for(int j = 0; j < COLUMNS; j++) {
                final JPanel cell = new JPanel();
                cell.setLayout(new BorderLayout());
                cell.setBorder(BorderFactory.createLineBorder(Color.RED));
                number = new JLabel(Integer.toString(logic.getValue(i, j)), 0);
                
                
               
                    final JButton cover = new JButton();
                    cover.setActionCommand(i + "" + j);
                    System.out.println(cover.getActionCommand());
                    cell.add(number);
                    cell.add(cover);
                    add(cell); 
    class MyMouseListener implements ActionListener
    {
    public void actionPerformed(ActionEvent event)
    {
    int cx = Integer.parseInt(cover.getActionCommand())/10;
    int cy = Integer.parseInt(cover.getActionCommand())%10;
    logic.setvalue2(cx, cy);  // sets the value of 2d array to 1 so it doesn't get drawn
    // cover.setVisible(false);
    System.out.println(cell.getComponentCount());
    cell.remove(1);
    
    }

  10. #10
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Mouse Listener and JButtons

    My recommendations are for one to make your Listener an inner private class, to create one ActionListener object before the loops and to add this single object to all the JButtons.

    In this listener, you could get the actionCommand String by calling this method on the ActionEvent parameter, and you could get the JButton that was pressed by calling getSource() on the ActionEvent object. Finally you could get the mine cell JPanel that holds the JButton by calling getParent() on the JButton.

    As for getting rid of the JButton and showing the underlying JLabel, the easiest and best way is to use a CardLayout to swap components for you. Otherwise you could remove the JButton from the mine cell JPanel by calling remove(button) on the JPanel as you're trying to do, but this can get tricky. For one, after removing a component you have to call revalidate and repaint on the JPanel to have it re-layout its components and repaint them, but if you do this:

    Java Code:
       private class MyMineButtonListener implements ActionListener {
          public void actionPerformed(ActionEvent event) {
             int cx = Integer.parseInt(event.getActionCommand()) / 10;
             int cy = Integer.parseInt(event.getActionCommand()) % 10;
             logic.setvalue2(cx, cy);
             
             JButton button = (JButton) event.getSource();
             JPanel mineCell = (JPanel) button.getParent();
             mineCell.remove(button);
             
             mineCell.revalidate();
             mineCell.repaint();
          }
       }
    You'll notice that the JLabel still isn't visualized. I think that this happens because while the JLabel is added "under" the JButton, it really isn't under the JButton. For it to be visualized, you may have to re-add it to the JPanel. This can be done in a round-about way by calling getComponents() on the JPanel, looping through them, finding a JLabel, and adding it to the JPanel:

    Java Code:
             JButton button = (JButton) event.getSource();
             JPanel mineCell = (JPanel) button.getParent();
             mineCell.remove(button);
             
             Component[] components = mineCell.getComponents();
             for (Component component : components) {
                if (component instanceof JLabel) {
                   mineCell.add(component);
                }
             }         
             mineCell.revalidate();
             mineCell.repaint();
          }
       }
    but again, the easiest way by far to swap components is with a CardLayout.

    Finally, your if / else blocks in your logic class is not very elegant and is very redundant and can be replaced by nested for loops and much simpler logic -- as I've discussed before with you, but which you've seemed to have ignored. :(

    Edit: If you used a CardLayout, the listener code could be as simple as this:

    Java Code:
       private class MyMineButtonListener implements ActionListener {
          public void actionPerformed(ActionEvent event) {
             int cx = Integer.parseInt(event.getActionCommand()) / 10;
             int cy = Integer.parseInt(event.getActionCommand()) % 10;
             logic.setvalue2(cx, cy);
             
             JButton button = (JButton) event.getSource();
             Container mineCell = button.getParent();
             CardLayout layout = (CardLayout) mineCell.getLayout();
    
             // NUMBER is a String constant and was the "constraint" object used
             // when the number JLabel was added to the JPanel.
             layout.show(mineCell, NUMBER);
          }
       }
    It doesn't come much easier than this.
    Last edited by Fubarable; 01-05-2012 at 04:55 AM.

  11. #11
    Danieldcc is offline Member
    Join Date
    Sep 2010
    Posts
    83
    Rep Power
    0

    Default Re: Mouse Listener and JButtons

    wuttt....thank you, thank you.....I was working so long on getting that to work.

    In regards to CardLayout.....I'll try it after I finish the coding for learning improvement purposes (the reason I didn't try it before is cause I didn't know about it and I was reading about the grid layout and I think someone here recommended it aswell so I went for it)

    As far as the logic suggestion from you. Yes I looked at it and plan to implement it after I get this game done for improvement aswell.

    As you can see, I'm a total newbie and everything takes me a really long time plus I have a full time job and a gf to entertain (lol)......but I'm starting a java class next week at the university and wanted to get this assignment done so I get practice and some knowledge before I start the course.

    tks again.

  12. #12
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default Re: Mouse Listener and JButtons

    Quote Originally Posted by Danieldcc View Post
    In regards to CardLayout.....I'll try it after I finish the coding for learning improvement purposes (the reason I didn't try it before is cause I didn't know about it and I was reading about the grid layout
    You're confusing things. You do need to use GridLayout for the overall container, the one that holds the grid of buttons. I'm talking about using CardLayout for the individual grid cells.

    As far as the logic suggestion from you. Yes I looked at it and plan to implement it after I get this game done for improvement aswell.
    Then why even ask the question at that time if you're not going to do anything with the advice? Sorry if I sound frustrated, but it is frustrating to put in effort only to have it ignored.

  13. #13
    Danieldcc is offline Member
    Join Date
    Sep 2010
    Posts
    83
    Rep Power
    0

    Default Re: Mouse Listener and JButtons

    Sorry, I was gona work on the logic part but when I ran into problems with the GUI i ignored the logic part for time being. I'll try the cardlayout. I'm just such a newbie that afraid to change things once they work

Similar Threads

  1. Need some help with mouse listener
    By Serialcek in forum AWT / Swing
    Replies: 8
    Last Post: 01-07-2012, 10:20 AM
  2. Mouse listener
    By chetoos in forum Advanced Java
    Replies: 3
    Last Post: 06-23-2011, 09:23 PM
  3. Need Help with Mouse Listener!!!!
    By Doggir in forum New To Java
    Replies: 11
    Last Post: 05-05-2011, 11:48 PM
  4. Mouse Listener
    By Quizerno in forum New To Java
    Replies: 8
    Last Post: 03-17-2011, 05:25 AM
  5. Mouse Listener for mouse floating over object?
    By Krooger in forum AWT / Swing
    Replies: 1
    Last Post: 11-18-2009, 04:34 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •