[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Getting an image from mouseClick co-orinates

Posted on 2005-04-21
19
Medium Priority
?
287 Views
Last Modified: 2010-03-31
Ok.
I have a canvas with images on it (a Crazy Eights card game).
I have a mouseClick event that tells me which co-ordinates I have clicked.
I have the co-ordinates mapped out so that when I click on one of the player's hands or piles, it says "you clicked on "whatever" hand."

BUT
I can't figure out how to actually get the image I clicked or how to pass values from the mouse click. I also have all of this code in the mouseClick event and I'm not sure I should, but it's the only way I could make it work so I just kept going. Here's some of the code just to give you an idea of what I'm doing vs what I should be doing.


public class CrazyEightsFrame extends JFrame{

........

private class mouseClickHandler extends MouseAdapter {
        public void mouseClicked(MouseEvent event) {
            int xPos = event.getX();
            int yPos = event.getY();
           
            int cardWidth = 140-90; // -90 is the card overlap
            int cardHeight = 217;
           
            int hand1 = playHand1Up.getCardCount()*cardWidth;      // number of cards in the hand
            int hand2 = playHand2Dn.getCardCount()*cardWidth;
            int handDiscard = discardHandUp.getCardCount()*cardWidth;
           
            if (xPos >= 10 & xPos <= hand1) {
                if(yPos >= 10 & yPos <= cardHeight)
                    System.out.println("Player 2's hand");
                handClicked = playHand1Up;
            }
            .......
            }

 public static void main(String[] args){....}


As always, suggestions are always welcome and if you have any questions, feel free to ask because I'll be sitting here all day trying to get this going.
0
Comment
Question by:liah00
  • 9
  • 8
17 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 13836941
0
 

Author Comment

by:liah00
ID: 13837027
Ok, I'm pretty sure I can figure out how to define my positions as rectangles, but after that, I'll be stuck again. Java confuses me....you have to hold my hand haha.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13837087
Another way is to put the images in JLabels and set the position of the labels in an absolute way. You can then add a mouselistener directly to the label
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:liah00
ID: 13837141
How much hassle would it be to switch over to labels? I was told it would be more hassle than it's worth. I want the easiest way possible because I'm running out of time.

I have no idea if you need it, but this is my image array.

Toolkit tk = Toolkit.getDefaultToolkit();
        // 2D array that stores the 52 cards of a deck. 4 Suits, 13
        // cards for each suit
        ImageIcon[][] cards = new ImageIcon[4][13];
        int iCardCounter = 1;
       
        for (int i=0; i<4; i++) {
            for (int j=0; j<13; j++) {
                cards[i][j] = new ImageIcon(tk.getImage("Cards\\card"+ iCardCounter + ".gif"));
                iCardCounter++;
            }
        }
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13837252
If you've gone without labels then you could do this sort of thing (imagine cards laid out at the following x-position - you may have to allowfor overlaps):


0      100      200      300

int xIndex = point.x / width; // (imagine point.x = 117. width is 100)
// therefore xIndex = 1

This will give you the x index of the array of objects. If the array contains images, then you'll have image at x index 1. You may need to determine y index too
0
 

Author Comment

by:liah00
ID: 13837528
Ok, even if I was following you, I still have no idea what the code for "this is the image clicked" is and I seem to have no way to pass any of this information into anything outside of the mouseClicked event. I'm so confused.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13837562
The Point in the mouseClicked event gives you a coordinate pair. Since you're not having listeners on the images, it's up to you to map the coordinates to something on your gui. You can call any method you like from the listener
0
 

Author Comment

by:liah00
ID: 13837647
That's insane! I can't believe my teacher would say that's the easiest way to do it. Maybe it is, but that seems like a lot of work. I have the coordinates mapped for the different hands (the images are already on the canvas), and he told me that once I had that done and I could determine which hand was being clicked, I'd be able to tell it to get the image from that hand. I thought I was moving forward but it seems I'm moving back.
0
 

Author Comment

by:liah00
ID: 13837672
Is there a way to add an action listener to each image AS I'm loading the image into the array (or drawing the image on the canvas)? Here's my drawCard method

void drawCard(Graphics g, Card card, int x, int y)
{

       g.drawImage(cardImages[card.getSuit()][card.getValue()-1].getImage(), x, y, this);
                String s, r;
                s = card.getSuitAsString();
                r = card.getValueAsString();
}
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13837680
>> I'd be able to tell it to get the image from that hand

Well all that is true and corresponds to what i've just said:

int xIndex = point.x / width; // (imagine point.x = 117. width is 100)
// therefore xIndex = 1
Image clickedImage = images[xIndex];

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13837694
>>Is there a way to add an action listener to each image AS I'm loading the image into the array (or drawing the image on the canvas)? Here's my drawCard method

You can only add a listener to a component, which is why i mentioned labels before
0
 

Author Comment

by:liah00
ID: 13837953
Ok, it's starting to make sense now. So where do I put this?

int xIndex = point.x / width; // (imagine point.x = 117. width is 100)
// therefore xIndex = 1
Image clickedImage = images[xIndex];

In my mouseClick event?
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 13838106
This can go anywhere in that event. It would get the correct image for x on row one. You need to do it for y too:

int xPos = event.getX();
 int xIndex = xPos / width; // need to calculate this based on image width
 Image clickedImage = cardImages[xIndex][0];
 
0
 

Author Comment

by:liah00
ID: 13838150
ok, I'll putter around and see if Ican get something going. Knowing me, it'll likely take a while and I'll probably be back with more questions before I get it going
0
 

Author Comment

by:liah00
ID: 13838947
I'm doing something seriously wrong. I can click some points that return an image where there IS an image, other points that return an image where there is NO image and then even more points where I get an out of bounds exception (Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 4). I've tried moving the code around to different spots changing xPos/width into width/xPos and everything I can possible think of.
0
 

Author Comment

by:liah00
ID: 13840086
Ok, I give up on the co-ordinates. I'm gonna try the labels...any thoughts on that?
0
 
LVL 86

Accepted Solution

by:
CEHJ earned 2000 total points
ID: 13841307
Here's an example - get the 'flag' image from half way up this page on the left next to 'Certification' etc:


import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.HashMap;
import java.util.Map;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;


public class Cards extends JFrame {
      CardListener cardListener;
      Map cardIndexes;

      public Cards() {
            cardIndexes = new HashMap();
      }

      private void setGui() {
            try {

                  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                  cardListener = new CardListener();
                  JPanel p = new JPanel();
                  p.setLayout(null);
                  ImageIcon icon = new ImageIcon("certification.gif");
                  int width = icon.getIconWidth();
                  int height = icon.getIconHeight();
                  JLabel[] cards = new JLabel[4];
                  int i, x, y;
                  i = x = y = 0;
                  while (i < cards.length) {
                        cards[i] = new JLabel(icon);
                        cards[i].addMouseListener(cardListener);
                        cards[i].setBounds(x, y, width, height);
                        cardIndexes.put(cards[i], "Card " + (i + 1));
                        p.add(cards[i]);
                        x += width;
                        y += height;
                        i++;
                  }
                  getContentPane().add(p);
            } catch (Exception e) {
                  e.printStackTrace();
            }
      }

      class CardListener extends MouseAdapter {
            public void mouseClicked(MouseEvent e) {
                  System.out.println("Clicked on card: " + cardIndexes.get(e.getSource()));
            }
      }

      public static void main(String[] args) {
            Cards cards = new Cards();
            cards.setGui();
            cards.setSize(200, 200);
            cards.setVisible(true);
      }

}
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
In this post we will learn different types of Android Layout and some basics of an Android App.
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.
Suggested Courses
Course of the Month19 days, 13 hours left to enroll

873 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question