Image coordinates in JPanel

Hi everyone,
I need help in getting coordinates of a image that I have loaded in a JPanel using JFileChooser. The file is on my computer and that it can be any image. With the just loaded image, i have positioned it at 0,0 using the g.draw(). I will be dragging the image around the panel and I have seen some other people using certain methods to drag the image around the panel. Lets say the image img = null;
I have tried img.getX(), img.getY() or
img.getLocation.x, img.getLocation.y, or
img.x, img.y or
but the compiler give me "Cannot resolved symbol" for all the above methods or maybe some of the methods but the point is, none of the above methods work. Did miss out something or do i have to include some class or something?
The reason i need to get the x,y for my image is to allow me to drag it around the panel. What i am looking for is to get the image coordinates x,y on the panel. As in the location of the image in the panel.
Thanks in advance for the help.

... I have seen some other people
using certain methods to drag the image around the
panel. Have you asked them how they do it?
Lets say the image img = null;
I have tried img.getX(), img.getY() or
img.getLocation.x, img.getLocation.y, or
img.x, img.y or
but the compiler give me "Cannot resolved symbol" for
all the above methods or maybe some of the methods but
the point is, none of the above methods work. Did miss
out something or do i have to include some class or
something?The something you're missing is the API. Make it your friend.
>
The reason i need to get the x,y for my image is to
allow me to drag it around the panel. What i am
looking for is to get the image coordinates x,y on the
panel. As in the location of the image in the panel.There are two common ways to do this:
1. Your custom panel directly drawing the image, so it has the job of knowing the image's position.
Why not make imageX and imageY fields of your panel class?
2. You custom panel class works like a Container, withe the image(s) being managed by a JLabel.
Then your panel will use a null LayoutManager or perhaps will be a JLayeredPane and the JLabel's
location is the location of the image.

Similar Messages

  • How do I draw an image on a JPanel?

    To be honest I have no idea even where to start. I tried hacking through the tutorials but it just didn't help me (normally they do, I don't what's up).
    Anyway, so what I'm trying to do is build a game. The Graphics2D is great for simple shapes but drawing characters is getting kind of ridiculous (tedious + difficult + looks bad). So, I need to figure out how to display an image on a JPanel.
    To that end I have several questions.
    1 - What image type do I use? Like jpeg, bmp, gif, etc.
    2 - How do I make parts of it transparent?
    3 - How do I make it appear on the screen, given some coordinates on the JPanel?

    To draw an image directly to a JPanel given certain coordinates, you have to create a custom JPanel and override its paintComponent() method. Like this:
    class PaintPanel extends JPanel{
    public void paintComponent(Graphics g){
    super.paintComponent(g);
    //painting code goes here}
    }Java can load in and draw GIF and JPEG images. If you decide to use GIF files, any good image editor like Adobe Photoshop should be able to make them transparent for you before the fact. If you want to set transparency within your java program you will have to create a BufferedImage and make certain colors within it transparent, but I would like to know how to do that as much as you do.

  • Animated GIF Image on a JPanel.

    How can I display an animated GIF image on a JPanel? It should animate after displaying.
    Regards

    I think this code should display an animated GIF image on a JPanel.
    -Mani
    import javax.swing.*;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import java.awt.*;
    public class Animation {
    public static void main(String args[]) {
    JLabel imageLabel = new JLabel();
    JLabel headerLabel = new JLabel();
    JFrame frame = new JFrame("JFrame Animation");
    JPanel jPanel = new JPanel();
    //Add a window listner for close button
    frame.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    System.exit(0);
    // add the header label
    headerLabel.setFont(new java.awt.Font("Comic Sans MS", Font.BOLD, 16));
    headerLabel.setText("Animated Image!");
    jPanel.add(headerLabel, java.awt.BorderLayout.NORTH);
    //frame.getContentPane().add(headerLabel, java.awt.BorderLayout.NORTH);
    // add the image label
    ImageIcon ii = new ImageIcon("d:/dog.gif");
    imageLabel.setIcon(ii);
    jPanel.add(imageLabel, BorderLayout.CENTER);
    frame.getContentPane().add(jPanel, java.awt.BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
    }

  • How to get Image Coordinates in a Frame

    Hi,
    I want to retrieve Image Coordinates contained in a Frame.
    I am able to get the frame coordinates through IGeometry but not the images.
    Any help will be highly appreciated.
    Regards,
    Rahul Rastogi

    Hi
    SnpGraphicHelper in SDK provides code for getting IImageDataAccess for given Frame ref. Use GetUID to get uid of the image from IImageDataAccess, obtained above.
    Once you get UID, you should be able to get its geometry.
    Rajani

  • How to use a backgroud image in a JPanel.....

    hi,
    How can I display a background image for a JPanel.....
    I have searched this forum but all solutions I found are where JPanel at the end has to be displayed on a frame in an application...
    I need to use JPanel on Applet.......
    Actually I am switching JPanels on JApplet as screens for a game....
    I need to display background image for one of the JPanel class that has to be called by an Applet class....
    Thanks a lot for any help.

    Thanks a lot for your help.
    How do we specify URL to use an image from net. Is itt like I open an image file on some website & use its address? Kindly add here some website too so that its more clear for me.
    Thanks a lot for any help & all help your provided previously.
    String imageFilePath = "urlOfMyImageFile"; // I am asking about parameter to be used here
    ImageIcon ii = new ImageIcon(imageFilePath);
    Image image = ii.getImage();

  • How to add an image to a JPanel ?

    hi,
    do you now how to add an image to a JPanel ?
    thanks a lot !

    You can either use the Graphics method drawImage from the panel's paintComponent(Graphics g) method, or you can create an ImageIcon, with your Image in its constructor. And then create a JLabel, passing that ImageIcon in its constructor. Then, you can simple use the panel.add() method to add that JLabel.
    For using the paintComponent method, check out the thread already posted above (I'll type it in again just in case)
    http://forum.java.sun.com/thread.jsp?forum=31&thread=288769
    If you want to use a JLabel, you can do something like this:
    Image img;
    JLabel label = new JLabel(new ImageIcon(img));
    JPanel panel = new JPanel();
    panel.setLayout(new FlowLayout());
    panel.add(label);Val

  • How to add an image in a JPanel

    Hi All,
    How to add an image in a JPanel and make it display.
    Thanks,

    I have tried with the below code. If I there is any fault please correct me.
    import java.awt.event.*;
    import java.awt.*;
    import javax.swing.*;
    public class HomePage extends JFrame implements     ActionListener {
        JButton cmdClick;
        JLabel label;
        JPanel homePanel = new JPanel();
        JPanel headPanel = new JPanel();
        JPanel btPanel = new JPanel();
        private JPanel mainPanel = new JPanel(new CardLayout());
        CardLayout cl;
        CalScenario calcFrame = null;
        public HomePage() {
           setTitle("Test Kit");
           setSize( 1008,399);
           setBackground( Color.gray );
           setResizable(false);
           Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
           Rectangle window = getBounds();
           setLocation((screen.width - window.width) / 2, (screen.height - window.height) / 2);
           setVisible(true);
            homePanel.setLayout(new BorderLayout());
            headPanel.setPreferredSize(new Dimension(1008,153));
            label = new JLabel("Main menu");
            headPanel.add(label);
            headPanel.setBackground(Color.CYAN);
            ImageIcon icon = new ImageIcon("images/slash.gif");
            JLabel imglabel = new JLabel();
            imglabel.setIcon(icon);
            headPanel.add(label);
            this.getContentPane().add(headPanel);
            btPanel.setBackground(Color.ORANGE);
            cmdClick = new JButton("Click here");
            btPanel.add(cmdClick);
            cmdClick.addActionListener(this);
            homePanel.add("North",headPanel);
            homePanel.add("West",btPanel);
            calcFrame = new CalScenario(mainPanel);
            mainPanel.add(homePanel, "HomePanel");
            mainPanel.add(calcFrame, "CalcFrame");
            cl = (CardLayout) (mainPanel.getLayout());
            add(mainPanel);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        public void actionPerformed(ActionEvent source)  {
          if (source.getSource() == (JButton) cmdClick) {
                cl.show(mainPanel, "CalcFrame");
        public static void main( String args[]) {
             HomePage homeFrame = new HomePage();
             homeFrame.setVisible(true);
    }

  • Trouble using images on a jpanel

    Hi!
    First off, I'm new to java so don't shoot me for asking a probably dumb question! I've been searching for the past 2 hrs on how to add an image to my jpanel.....problem is I'm completely confussed! I've found how to add one to an applet, but then to be told adding to an application is different...i thought i'd figured it all out but it's still not working.
    I've declared the image....and tried adding it to a label....but it didnt work.
    I'm sooo confused and getting frustated, somebody please help!
    Thanks,
    JenanaBanana

    Hi,
    You should try searching over the forum before posting....
    Here is a link to a similar post in this forum...
    http://forum.java.sun.com/thread.jspa?threadID=550457&messageID=2688013
    And here is some clumsy code from myside. It works beautifully though:
    import java.awt.BorderLayout;
    import java.awt.FlowLayout;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
    public class ImagePanel {
    //Adding an image to a frame
    private static void addimage(JFrame aframe){
              //Create ImageIcon
              ImageIcon aimage = new ImageIcon("C:\\myimage.gif");
              //Create JPanel
              JPanel apanel = new JPanel(new FlowLayout());
              //Add mage to JPanel... you will need to do it through a JLabel to achieve this
              apanel.add(new JLabel(aimage));
              //Add the panel istself to the Frame
              aframe.getContentPane().add(apanel, BorderLayout.CENTER);
    //showpanel method
    private static void showpanel(){
              try{
                   //I like Windows Look And Feel
                   UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
                   //Create a frame and set the Close operation.
                   JFrame myframe = new JFrame("Image on Panel");
                   myframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   //add the image component to the frame
                   addimage(myframe);
                   //display
                   myframe.pack();
                   myframe.setVisible(true);
              catch(Exception e){
                   System.out.println("Application Error. Printing Stack Trace: ");
                   e.printStackTrace();
                   System.exit(-1);
    //Main Class
         public static void main(String[] args) {
              //Create Runnable mythread
              Runnable mythread = new Runnable() {
                   public void run() {
                        showpanel();
              //run it
              SwingUtilities.invokeLater(mythread);
    Let me know if any of this helps...
    Thanks,
    -Vamsi

  • How do you change the image in a JPanel?

    Hey! (firstly, i need to use image on a JPanel, label&icon not an option).
    I've made my JPanel class
        public class DrawingPanel extends JPanel {
            Image img;
            DrawingPanel() {
                Image img = Toolkit.getDefaultToolkit().getImage("13.jpg"); //default image at startup
            public void paintComponent (Graphics g) {
                super.paintComponent (g);
                // Use the image width & height to find the starting point
                int imgX = getSize ().width/2 - img.getWidth (this);
                int imgY = getSize ().height/2 - img.getHeight (this);
                //Draw image centered in the middle of the panel   
                g.drawImage (img, 0, 0, this);
            } // paintComponent
        } // DrawingPanelAnd I've made my instance of it and added it to the Frame:
        DrawingPanel imagePanel = new DrawingPanel();Now, I need to change the image on the JPanel according to the user's input. I have the string of the location of the new image. How do I update the JPanel to display this new image? Any help greatly appreciated!!

    Well... You could just add a method in your class which sets the image according to the new image name you provided. Something like this:
        public class DrawingPanel extends JPanel {
            Image img;
            DrawingPanel() {
                img = Toolkit.getDefaultToolkit().getImage("13.jpg"); //default image at startup
            public void setImage(String imageName) {
                    img = Toolkit.getDefaultToolkit().getImage(imageName); //Loading the desired image
            public void paintComponent (Graphics g) {
                super.paintComponent (g);
                // Use the image width & height to find the starting point
                int imgX = getSize ().width/2 - img.getWidth (this);
                int imgY = getSize ().height/2 - img.getHeight (this);
                //Draw image centered in the middle of the panel   
                g.drawImage (img, 0, 0, this);
            } // paintComponent
        } // DrawingPanel

  • What code can i use to add an image to a JPanel?

    I tried multiple image tutorials and none of those supplied me with a way to add an image to a JPanel without using hidious code. Don't anyone know simpler code which i can use?

    Don't anyone know simpler code which i can use?Simpler than what? Post what you've got at the moment. Use code
    tags as described here: http://forum.java.sun.com/help.jspa?sec=formatting
    About the simplest I can think of is to make a JLabel using the
    constructor that takes an Icon argument, and then add it to the JPanel.
    (The Swing forum is the best place for this.)

  • Add Image icon to jpanel

    I have to add an image to a jpanel.
    I am using the below code
    I have already defined the jlabel(lblImageIcon) using the netbeans design palette and made the jlabel visibility false.
    lblImageicon=new JLabel
    lblImageicon.setText("ImageIcon")
    gridBagConstraints =new java.awt.GridBagConstraints
    gridBagConstraints .gridX=2
    gridBagConstraints .gridY=2
    add(lblImageIcon,gridBagConstraints )
    Then when I have to show the image upon a condition I have the following
    ImageIcon icon = new ImageIcon("http://ipaddress/test/test.png)
    lblImageIcon.setIcon(icon)
    lblImageicon.setVisible(true)
    The iamge does not show up.If I do a system.out afetr the line
    ImageIcon icon = new ImageIcon("http://ipaddress/test/test.png)
    It show as http://ipaddress/test/test.png)
    I am not sure whether it is reading the image or not showing the image because of size.Also my application uses applet and I am signing the applet.
    Is there any other way to add the images or what am I doing wrong or missing.
    Thanks,

    The code is without code tags (read the 2nd post of the forum), the link is broken, and an SSCCE would still be the best.

  • How will I put a background Image in a JPanel?

    Can you help me on how will I put a background image in a JPanel?
    And also in a JDeskTopPane?

    Hint:
    Search the forum using two keywords in your subject. This question had been asked many times.

  • Using mouse click to return image coordinates.

    Ok so I've been trying to figure out how to do this and it seems very complicated for something that really seems straightforward.
    Anyway. I have a camera that updates an image object on the front panel using a while loop. I have another image object that is updated with a still image when the "snap" button is pressed. Now what I want to do is to click on a point in the snapped image and have the VI return the coordinates of that pixel in the image coordinate frame.
    What I've got so far is an event structure in the while loop with the following to occur in the event "image object -> mouse down":
    Server reference (reference to the image object) -> Property node (last mouse position) -> output screen coordinates.
    I've got two errors that don't make a whole lot of sense to me (I haven't worked with event structures before): "event data node contains unwired or bad terminal" and "event structure one or more event cases have no events defined". This second one seems strange since I don't actually want anything to happen if there's no mouse click. The first one seems to refer to the element box on the left hand side of the event structure.
    The above is my lastest attmpt at sorting this problem and as far as I can see it should work. whatever about the errors, am I even taking the right approach with this? I'd have thought image cordinates would be a common enough thing but search the boards here, it would appear not...
    Kinda stumped here. Any help is much appreciated.
    Message Edited by RoBoTzRaWsUm on 04-14-2009 08:34 AM
    Solved!
    Go to Solution.

    Hello RoBoTzRaWsUm,
    I have taken a look at your VI, which has been taking a correct approach to the data you are looking for.  As you are using and event structure, you should be looking for an event to occur.  When using a Property Node, you are trying read an attribute of a control.  However, in an Event Structure, I believe you should be using an Invoke Node.  An Invoke Node allows your to read an event or write a method with the Control Class in LabVIEW. 
    1. Place down and Invoke Node from the Functions Palette in 'Programming'->'Application Control'
    2. Wire your Image Control reference to it
    3. Click Method, and select 'Get Last Event'
    4. Right click on 'Which Events' and 'Create Constant'.  Make the constant '1' in the array
    5. Read the 'Coordinates' Cluster from the left hand side of the Event Case by right clicking  and 'Create Indicator'
    You will find a piece of example code attached.
    Regards
    George T.
    Applications Engineering Specialist
    National Instruments UK and Ireland
    Attachments:
    UKSupportMouseClick.vi ‏39 KB

  • Showing an image in a JPanel

    Hi all!
    I'm developing an applet that shows an image in a JPanel when it is clicked. The problem is that when the code that shows the image is placed in the mouseClicked() method, nothing happens...
    Any idea would be appreciated.
    Thanks in advance.
    Applet's code:
    package test;
    import java.awt.*;
    import java.awt.event.*;
    import java.applet.*;
    import javax.swing.*;
    import java.awt.image.*;
    import javax.imageio.*;
    import java.io.*;
    public class ImageMouseClick extends JApplet implements MouseListener{
      private boolean isStandalone = false;
      JPanel jPanel1 = new JPanel();
      JPanel jPanel2 = new JPanel();
      GridBagLayout gridBagLayout1 = new GridBagLayout();
      BufferedImage bufi;
      //Get a parameter value
      public String getParameter(String key, String def) {
        return isStandalone ? System.getProperty(key, def) :
          (getParameter(key) != null ? getParameter(key) : def);
      //Construct the applet
      public ImageMouseClick() {
      //Initialize the applet
      public void init() {
        try {
          jbInit();
        catch(Exception e) {
          e.printStackTrace();
      //Component initialization
      private void jbInit() throws Exception {
        this.getContentPane().setBackground(Color.white);
        this.setSize(new Dimension(400,300));
        jPanel1.setLayout(gridBagLayout1);
        jPanel2.setBackground(Color.white);
        this.getContentPane().add(jPanel1, BorderLayout.CENTER);
        jPanel1.add(jPanel2,  new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0
                ,GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(72, 82, 81, 100), 208, 137));
        jPanel2.addMouseListener(this);
        File f = new File("/home/***/myimage.gif");
        try {
          bufi = ImageIO.read(f);
        } catch (IOException ioe){
          System.out.println("IO Error");
      public void mouseClicked(MouseEvent me) {
        //Add image to JPanel2
         JLabel showWorld = new JLabel(new ImageIcon(bufi));
        jPanel2.add(showWorld);
        jPanel2.setVisible(true);
        System.out.println("Click!");
      public void mousePressed(MouseEvent me) {
      public void mouseExited(MouseEvent me) {
      public void mouseEntered(MouseEvent me) {
      public void mouseReleased(MouseEvent me) {
      //Get Applet information
      public String getAppletInfo() {
        return "Applet Information";
      //Get parameter info
      public String[][] getParameterInfo() {
        return null;
      //static initializer for setting look & feel
      static {
        try {
          //UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
          //UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        catch(Exception e) {
    }

    In the event loop (handling the mouse click) redrawing is not done.
    You could try to add a showWorld.repaint(100L); for a later repaint.
    A more general solution is SwingUtilities.invokeLater(...);; for that better read the javadoc.

  • Put an Image to a JPanel

    Is there an easy way to put a Image to a JPanel (or as a background for the JPanel). Or is there some kind of JImagePanel class that I can use.

    Hi,
    put JLabel into JPanel and an image put into JLabel. And next time try to search the forum first.
    L.P.

Maybe you are looking for

  • My Mac Book Pro changes the saved home page each time I start Safari.  I also get new tabs that randomly open asking to clean up my Apple

    My Mac Book Pro changes the saved home page each time I open Safari.  I am also getting random tabs opening with various "cleaning up" my computer junk. How do I get rid of this?  I tried some of the fixes listed but they don't seem to work or I am d

  • Finding  View name in screenflow jsp in obpm 10g

    Hi, We have a following requirement We are displaying a alert box in screenflow jsp upon certain conditions if the user is opening the instance from Inbox or any otehr custom views except History View. If the user is opening instance jsp from history

  • How to map the permits Scenarios

    Dear Experts, Good Morning  to Every to Body. I am confusing to map the permits scenario . In my client place they raise the Work permit request to the Safety Officer for getting the approval for doing their work. Based on working condition safety of

  • Question about  Graphics Cards for Adobe and more

    Hello, for technical people I'll start by listing some relevant computer info:    Asus P9x79Pro Motherboard . Nvidia Quadro 4000 2GB . Windows 7 . Adobe CS6 I have a workstation PC and have been considering ways to improve it. I'm pretty happy with b

  • License Expiration Part 2

    I am wondering if sometime around April 2010, Adobe pulled or disabled the license for CS3 Master Collection.  It had been working fine on my Windows Vista Premium Home machine and then I got a message about deactivating the license.  Not understandi