Coordinates on jlabel

hi, was wondering how to return the coordinates of a mouse click event on an image on jLabel. well, my code does do that, but when i change the window size, the coordinates change as well, i need to know the coordiantes of the pixel of the image in the jLabel inside a panel :o(

thanks, that looks mighty helpful, but even after reading the API, i couldn't figure out what the "destination" would be, the source would be the JPanel components, but for destination what I want is for it to be the exact size as that of the image, if you know what i mean

Similar Messages

  • Setting absolute coordinates of a JLabel

    Is it possible to set absolute (x,y) coordinates using JLabel? Thanks a bunch!

    way112 wrote:
    Is it possible to set absolute (x,y) coordinates using JLabel? Thanks a bunch!Or using setBounds(....) method but I would recommend using a proper layout
    so that you won't have a hard time setting the components.

  • Positioning problems

    Is there anyway to specify the coordinates for JLabels and buttons? Here is some code I am working on right now:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Tutorials extends JApplet implements ActionListener
    FlowLayout flow = new FlowLayout();
    private Button but1, but2, but3, but4;
    JLabel titleBar = new JLabel("Tutorials");
    Font defFont = new Font("Verdana", Font.PLAIN, 14);
    public void init()
    Container con = getContentPane();
    con.setLayout (new FlowLayout());
    titleBar.setFont(defFont);
    con.add(titleBar);
    con.add(greet);
    but1 = new Button("Tutorial 1");
    con.add(but1);
    but2 = new Button("Tutorial 2");
    con.add(but2);
    but3 = new Button("Tutorial 3");
    con.add(but3);
    but4 = new Button("Exit HTML Tutorials");
    con.add(but4);
    etc...
    I would like to specify where everything goes, labels, buttons, textfields, etc...
    Also, how would I open new "windows" using these buttons? And how would I close them using a button in the newly opened windows? Would I need different classes for each of the different windows or could I use methods inside my class file?
    (Sorry if this seems remedial, but I am not good with programming in general and I am hoping this is my last programming class.)
    Thanks a bunch,
    Eros

    import ...
    class ... extends JFrame {
    setBounds(12, 34, 234, 432);
    getContentpane().setLayout(null);
    JButton jb = new JButton("jbutton");
    jb.steBounds(11, 22, 33, 22);
    getContentpane().add(jb);
    setVisible(true);
    BTW, that question has been covered in this forum allready some time ago. google for absolutlayout

  • I just want to set my Jlabels coordinates, how hard can that be???? HELP

    hey, basically this is the first time ive ever touched java therefore bear with me. Basically all i want to do is set an images coordinates so its where i want it to be. i want the image to stay there permently.
    Please help
    import javax.swing.JFrame;
    import java.awt.image.BufferedImage;
    import javax.swing.Timer;
    import javax.swing.ImageIcon;
    import java.awt.FlowLayout;
    import javax.swing.JLabel;
    public class Main
    public static void main(String[] args)
    JLabel image=new JLabel(new ImageIcon("image.gif"));
    frame.add(image);
    rame.setVisible(true);

    hey, basically this is the first time ive ever
    touched java therefore bear with me. Basically all i
    want to do is set an images coordinates so its where
    i want it to be. i want the image to stay there
    permently.Two options.
    Option A:
    Use a null LayoutManager for your JFrame and explicitly set the bounds of the JLabel:
    frame.setLayout(null);
    image.setBounds(x,y,w,h);  // x,y,w,h are calculated by you somewhere else
    frame.add(image);Option B:
    Paint the image on the JFrame directly by overriding its painting code.
    Neither option is a good idea. What exactly are you trying to create?

  • How to get coordinates of components. PLEASE HELP ME URGENT!

    Hi, I am trying to get the coordinates of my components that are tabbed pane buttons, buttons, text fields etc so I can place an image of a pointer under it that points to it and then under the image of the pointer I would put a label describing the button for example "press the tab to start". Then when I press tab1 the image of pointer image points to the next component and has a label under pointer.
    Now I have tried using componenet.getX() and getY() and then set the values of the the image panel to use then the label panel so they be placed under the component, these panels are not using layout manager but absolute positioning. If the window is resized then the labels and image of pointer should also adjust. I have tried putting the label and arrow into a glasspane and now layerdpane as some people here suggested which when I do then add it to contentpane the main panel with the components is not there but the layerd pane is.
    I am having huge difficulties with this and if someone can Please just tell me or even better give me an example code how to find out the coordinates of components so I can place my image of pointers and labels underneath them I will be very grateful of you. I am on a verge of giving up accomplish what I am doing and I am new to the swing framework. My progress to solve this has been very slow and frustrating. I just hope someone here can help.

    I tried the both of codes given. But the code given by both the person i have not understand. And what they there code is doing. This is the code form my side if this example help u.
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    * Author Waheed-Ul-Haq ( BS(CS)-8 )
    public class Samulation2
         JPanel pane;
         JLabel label1;
         JTextField entProcesfld;
         JButton buttCreat;
         JButton buttReslt;
         JLabel usrProcesID[];
         JTextField usrArivTam[];
         int processes;
         public JComponent createComponents()
         pane = new JPanel();
         pane.setLayout (null);     
         label1 = new JLabel();     //Label for to tell user to enter no of Processes.
         label1.setText("Enter the no. of Processes");
         pane.add(label1);
         label1.setBounds(20, 25, 150, label1.getPreferredSize().height);
         entProcesfld = new JTextField();     //TextField to enter no of processes.
         entProcesfld.setToolTipText("Enter the no of Processes.");
         pane.add(entProcesfld);
         entProcesfld.setBounds(180, 25, 100, entProcesfld.getPreferredSize().height);
         buttCreat = new JButton();          //Button to create the TextFields.
         buttCreat.setText("Create TextFields");
         pane.add(buttCreat);               //Adding cutton to Jpane.
         buttCreat.setBounds(new Rectangle(new Point(30, 60), buttCreat.getPreferredSize()));
         buttCreat.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        buttCreatActionPerformed(e);
                   } } );          //ActionListenr to Create the TextFields.
         pane.setPreferredSize(new Dimension(600,600));
         return pane;
         }     //-------END of Component createComponents()--------//
         private void buttCreatActionPerformed(ActionEvent e)     //Action to Create the TextFields.
                   processes = Integer.parseInt (entProcesfld.getText ());
                   JLabel Labproces = new JLabel();     //Label of Processes.
                   Labproces.setText("Processes");
                   pane.add(Labproces);
                   Labproces.setBounds(new Rectangle(new Point(15, 105), Labproces.getPreferredSize()));
                   JLabel labArivTam = new JLabel();     //Label of Arival time.
                   labArivTam.setText("Arrial Time");
                   pane.add(labArivTam);
                   labArivTam.setBounds(new Rectangle(new Point(90, 105), labArivTam.getPreferredSize()));
                   //----Creating Dynamic JLabels------//
                   usrProcesID  = new JLabel[processes];     /* Makes an array */
                   int yXis = 125;          //Variable for Y-axix of JLabel.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
                    usrProcesID[i] = new JLabel("P" + i);      /* Makes a JLabel at an array place */
                    pane.add(usrProcesID);      /* Adds a JLabel (rather than an array) */
    usrProcesID[i].setBounds(new Rectangle(new Point(28, yXis), usrProcesID[i].getPreferredSize()));
    yXis = yXis + 25;     /* Increses the Y-axis to show JLabels. */
    }     //EndFor     
    //-------End Dynamic JLabels---------//               
                   //-----Creating Dynamic Arival Time TextFields-----//
                   usrArivTam = new JTextField[processes];          /* Makes an array */
                   yXis = 125;          //Variable for Y-axix of JTextField.
                   for(int i=0; i<processes; i++)      /* i takes each value from 0 to processes-1 */
    usrArivTam[i] = new JTextField();     /* Makes a JTextField at an array place */
    usrArivTam[i].setToolTipText("Enter Arival Time.");
    pane.add(usrArivTam[i]);      /* Adds a JTestField (rather than an array) */
    usrArivTam[i].setBounds(100, yXis, 35, usrArivTam[i].getPreferredSize().height);
    yXis = yXis + 25;     /* Increses the Y-axis to show JTextFields. */
    }     //EndFor     
    //-----End Dynamic Arival Time TextFields.-----//
    //----Calculating points for Label and textfields.
    Point poi = new Point();
    poi = usrArivTam[processes-1].getLocation ();     //Getting the location of the last text field of ArivalTime.
    //-----Label for Average Waiting time.--------\\
    JLabel averWaitLB = new JLabel();
    averWaitLB.setText("Average Waiting Time");
              pane.add(averWaitLB);
              averWaitLB.setBounds(new Rectangle(new Point(30, (int)poi.getY()+50), averWaitLB.getPreferredSize()));
    //-----TextField for Average Waiting Time.--------\\
    JTextField averWaitTF = new JTextField();
    averWaitTF.setText ("Hello");
    averWaitTF.setEditable(false);
    pane.add (averWaitTF);
    averWaitTF.setBounds(190, (int)poi.getY()+50, 35, averWaitTF.getPreferredSize().height);
    }     //------END of void buttResltActionPerformed(ActionEvent e)---------//
         private static void createAndShowGUI()
    //Make sure we have nice window decorations.
    JFrame.setDefaultLookAndFeelDecorated(true);
    //Create and set up the window.
    JFrame frame = new JFrame("Priority Scheduling (Non-Preemptive)....");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    Samulation2 application = new Samulation2();
    //Create and set up the content pane.
    JComponent components = application.createComponents ();
    components.setOpaque (true);
    int vertSB = ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS;
              int horzSB = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS;
              JScrollPane scrollPane = new JScrollPane(components, vertSB, horzSB);
    scrollPane.setPreferredSize (new Dimension(720,455));
    frame.getContentPane ().add (scrollPane,null);
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    }     //------END Of void createAndShowGUI()--------//
         public static void main(String[] args)
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    createAndShowGUI();
         }     //---------End of main()----------------//
    }     //--------END of class Samulation2----------//
    If any body help me implementing the ScrollBars in this code. I am unable to use Scroll Bars with this code while using NULL layout. If any body tell me how to get the Size and set for the pane.

  • Set location for the JLabel

    Hello!
    I've got an interesting effect and I don't have a list idea why it happens. I set layout to null in the panel and created some JLabels in this panel. Then I saved locations of the labels in a data base, exited from the window and tried to create the panel and labels again using information saved in the data base. All labels appeared in the panel but their locations were slightly different in spite of the coordinates were the same as befor. The top left corner of each label slightly displacemnts to the up and left. I used setLocation method in the JLabel and also tried to use setBound but result was the same.
    Does anybody know what the matter is?
    TIA

    you can use HelpBroker.setLocation and HelpBroker.setSize, but both are new methods introduced in JavaHelp 2.0 beta release only.

  • Setting JLabels to be on top.

    I'm making a Deck Card that shuttle and sorts the card. I was able to display the images using a JLabel with ImageIcon. I can get to display the images and everything, but my only problem is when i'm display the image that the first image is on top of the second and the second is on top of the third.
    I want it to display the opposite order so I want the first one to be under the second and the second to be under the third.
    Is there a way that I can get the a label to be on top of the other?
    I forgot to mentioned that they have different X and Y Coordinates.

    Actually in any panel etc you have a layout which layouts the componsnts in his own way. So you need a layout that displays components as they are.
    Try running following code:
    import java.awt.*;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.border.LineBorder;
    public class LayoutPanel extends JPanel {
       public LayoutPanel() {
          setLayout( new EmptyLayout( new Dimension( 400, 300 ) ) );
          JLabel[] labels = new JLabel[10];
          for( int i = 0; i < 10; i++ ) {
             labels[i] = new JLabel( "Label " + i );
             labels.setVerticalAlignment( JLabel.TOP ); // show text at top position
    labels[i].setLocation( 13 * i, 13 * i ); // set location
    labels[i].setSize( new Dimension( 100, 100 ) ); // set size
    int colour = i + 10;
    labels[i].setBackground( new Color( 9 * colour, 10 * colour, 11 * colour ) );
    labels[i].setBorder( new LineBorder( Color.black, 1, true ) ); // set border
    labels[i].setOpaque( true ); // set to draw its all pixels
    add( labels[i], 0 ); // set at top means last on top, otherwise use add(labels[i]) to set first on top
    public static void main( String argv[] ) {
    JFrame frame = new JFrame( "Polygon Demo" );
    LayoutPanel layout = new LayoutPanel();
    frame.setContentPane( new JScrollPane( layout ) );
    frame.pack();
    frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
    frame.setVisible( true );
    class EmptyLayout implements LayoutManager {
    private Dimension size = null;
    EmptyLayout( Dimension size ) {
    this.size = size;
    public void addLayoutComponent( String name, Component comp ) {}
    public void removeLayoutComponent( Component comp ) {}
    public Dimension preferredLayoutSize( Container parent ) {
    return size;
    public Dimension minimumLayoutSize( Container parent ) {
    return size;
    public void layoutContainer( Container parent ) {}
    Regards,
    Humayun

  • ImageIcon Array and a JLabel

    Hey,
    I have an ImageIcon arrary and JLabel called ImageLabel on which the ImageIcon is. Bascically I want it to do this: if the ImageIcon on the ImageLabel is a certain icon, say [0] and the click was < 200, then set the ImageIcon to [1] (in effect changing what image is shown on the ImageLabel). And vice versa, as demonstrated by the following code:
    if (x < 200) and (ImageIcon theIcon = [0]) // if the click is below 200 on the x axis and theIcon is [0]
              setImageLabel.setIcon(ImageIcon[1]);if (x > 200) and (ImageIcon theIcon = [1]) // if the click is above 200 on the x axis and theIcon is [1]
              imageLabel.setIcon(ImageIcon[2);
    However that code doesn't work. What code would work?

    Thank you for your reply. I tried using the code, however, I am unsure as to how to use a 2D array.
    I think it may help if I elaborate on what I need to do:
    I have 80 images, and would like each image to be assigned to a coordinate, such as 1,1 on a coordinate
    plane that is 16 wide by 23 high. My first idea would be that you will need (16 * 23) = 368 images, not 80.
    By having each image as an integer, I could then set it to load another image when clicked.
    For instance I want the program to load with the image set to 1,1 (this image
    would be "images/1-1.gif".)
    Now, since you are on 1,1 and click on a certain area of the image, it loads 2,1 (that co ordinate having the image "images/2-1.gif". If you click on a different part of the 1,1 image, it would load 3,1 ("images/3-1.gif). etc.
    Sorry to say it, but you're still unclear on your goal: will you be only displaying one image at a time ? Do you expect 1 image
    to represent each of the (16 * 23) coordinates ? Do you mean that the label will change location depending on the mouse clicks ?
    Whatever your objective is, I don't see what is incompatible with the code I suggested in my previous reply.

  • Map coordinates in MapViewer

    Hi,
    I have a Java application that submit requests to MapViewer. MapViewer4s response is a XML document, something like:
    <?xml version="1.0" encoding="UTF-8" ?>
    <map_response>
    <map_image>
    <map_content url="http://map.oracle.com/output/map029763.gif" />
    <box srsName="default">
    <coordinates>-122.260443,37.531621 -120.345,39.543</coordinates>
    </box>
    <WMTException version="1.0.0" error_code="SUCCESS"/>
    </map_image>
    </map_response>
    Thus, what I do is using a JLabel to show the image in the URL returned by MapViewer.
    All of this is working fine. Now I4m trying to make something more complicated.
    What I want to do is caught the user4s mouse click in the image and translate the point in which the user clicked (pixels) to a point in the map coordinates (longitude, latitude).
    How can I do this ? What API may I use ?
    Thanks,
         Rodrigo

    The <BOX> element in the XML map response gives you the bounding box of the returned map image, in user's coordinate space.
    Now you can get the mouse click's x,y in terms of pixels, and you also know the map image's width/height in terms of pixels. It should be easy to translate the click's position into user space.
    lj

  • How to show staticly decleared int's in a JLabel

    hi
    how to show staticly decleared int's in a JLabel
    i have the following code but it doesnt seem to be working
           // Declear jlabel
            JLabel statuslabel = new JLabel(" X Axis : " + x + " Y Axis : + y ");
           // position of cursor
            public static int x;
            public static int y;
           

    nicchick wrote:
    um is there a easyer way to update int's inside a JLabel:)You need a MouseMotionListener
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    public class CursorPositionInLabel
      private static final String BAD_LABEL = "Bad Label";
      private static final String GOOD_LABEL = "Good Label";
      private JPanel mainPanel = new JPanel();
      private Point cursorP = new Point();
      private JLabel badLabel = new JLabel(BAD_LABEL + ";  [" + cursorP.x + ", " + cursorP.y + "]"); // this guy never gets updated, & so never changes
      private JLabel goodLabel = new JLabel(GOOD_LABEL + ";  [" + cursorP.x + ", " + cursorP.y + "]");
      public CursorPositionInLabel()
        mainPanel.setPreferredSize(new Dimension(600, 600));
        mainPanel.setLayout(new GridLayout(1, 2));
        JPanel badPanel = new JPanel();
        badPanel.add(badLabel);
        JPanel goodPanel = new JPanel();
        goodPanel.add(goodLabel);
        mainPanel.add(badPanel);
        mainPanel.add(goodPanel);
        mainPanel.addMouseMotionListener(new MouseAdapter()
          // this is the event that gets tripped each time the mouse moves
          public void mouseMoved(MouseEvent e)
            // get the location of the mouse curse
            cursorP = e.getPoint();
            // and then update your JLabel with the coordinates
            goodLabel.setText(GOOD_LABEL + ";  [" + cursorP.x + ", " + cursorP.y + "]");
      public JPanel getMainPanel()
        return mainPanel;
      // create the JFrame in a thread-safe manner as the Sun tutorials tell us to do.
      private static void createAndShowUI()
        JFrame frame = new JFrame("CursorPositionInLabel");
        frame.getContentPane().add(new CursorPositionInLabel().getMainPanel());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    }Edited by: Encephalopathic on Jun 18, 2008 5:28 PM

  • 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.

  • Getting coordinates

    Hello group,
    I have a Container, containing various JComponents, and one of them is a JScrollPane containing a JLabel, and the JLabel contains an Image.
    When I click on the image, how to get the (x,y) relative to the origin of the image ?
    I make the JLabel listening to MouseClicks, but I that way I get translated coordinates.
    Sorry, the question is elementary, but my various attempts failed.
    Many thanks

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class Relativity
        JLabel origin, image;
        private JLabel getLabel()
            ImageIcon icon = new ImageIcon(getImage());
            JLabel label = new JLabel(icon);
            label.addMouseMotionListener(new Scanner());
            return label;
        private JPanel getOutputPanel()
            origin = new JLabel(" ", JLabel.CENTER);
            image  = new JLabel(" ", JLabel.CENTER);
            Dimension d = origin.getPreferredSize();
            d.width = 125;
            origin.setPreferredSize(d);
            image.setPreferredSize(d);
            JPanel panel = new JPanel(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.insets = new Insets(4,2,4,2);
            gbc.weightx = 1.0;
            addComponents(new JLabel("label origin"), origin, panel, gbc);
            addComponents(new JLabel("image origin"), image,  panel, gbc);
            return panel;
        private void addComponents(Component c1, Component c2, Container c,
                                   GridBagConstraints gbc)
            gbc.anchor = GridBagConstraints.EAST;
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            c.add(c1, gbc);
            gbc.anchor = GridBagConstraints.WEST;
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            c.add(c2, gbc);
        private BufferedImage getImage()
            BufferedImage image = null;
            try
                URL url = getClass().getResource("images/cougar.jpg");
                image = ImageIO.read(url);
            catch(MalformedURLException mue)
                System.err.println("url: " + mue.getMessage());
            catch(IOException ioe)
                System.err.println("read: " + ioe.getMessage());
            return image;
        private class Scanner extends MouseMotionAdapter
            public void mouseMoved(MouseEvent e)
                JLabel label = (JLabel)e.getSource();
                Point p = e.getPoint();
                origin.setText("x = " + p.x + "  y = " + p.y);
                Rectangle r = getImageRect(label);
                String s = "";
                if(r.contains(p))
                    s = "x = " + (p.x - r.x) + "  y = " + (p.y - r.y);
                image.setText(s);
            private Rectangle getImageRect(JLabel label)
                Dimension d = label.getSize();
                Icon icon = label.getIcon();
                int w = icon.getIconWidth();
                int h = icon.getIconHeight();
                Rectangle r = new Rectangle(w, h);
                r.x = (d.width - w)/2;
                r.y = (d.height - h)/2;
                return r;
        public static void main(String[] args)
            Relativity test = new Relativity();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JScrollPane(test.getLabel()));
            f.getContentPane().add(test.getOutputPanel(), "South");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
    }

  • Problem setting ImageIcon onto JLabel

    Hi guys I am currently writing a Pente board game.
    Now I have two classes called Stone and GameStatus.
    In the GameStatus constructor it basically generates a JPanel and I try to fill it with 19 x 19 JLabel and add a mouselistener to each of them. This way when the label gets clicked, I can change the Image of it to represents empty spot, with white stone or with black stone.
    Here is the code of Stone class
    package pente;
    import javax.swing.*;
    public class Stone extends JLabel
      // the color of the Stone object
      private String color;
      private int x, y; // the location of current Stone
      boolean occupied; // see if the spot is occupied
      // the location of each image file
      private final String EMPTY = "c:/empty.jpg";
      private final String BLACK = "c:/black.jpg";
      private final String WHITE = "c:/white.jpg";
      // private JLabel label = new JLabel();
      * The default constructor that initializes a
      * Stone object with a given color.
      public Stone(int x, int y, boolean o, String c)
          this.x = x;
          this.y = y;
          this.occupied = o;
          this.color = "empty"; // the color has not yet been set
          this.setIcon(new ImageIcon(EMPTY));
        // assign the given color to the Stone
       * This method sets the image of the current object depends on
       * the given variable c.
       * @return the Stone object with an appropriate image on it
      public Stone setColor(String c)
          // swtich the image of the Panel depends on the c given
          if ((c.equals("w")) || (c.equals("white")))
            this.color = "white";
            this.setIcon(new ImageIcon(WHITE));
          else if ((c.equals("b")) || (c.equals("black")))
              this.color = "black";
              this.setIcon(new ImageIcon(BLACK));
          return this;
       * This method replaces the current image with the empty image
       * @return the Stone object with empty image on it
      public Stone setEmpty()
          this.color = "empty";
          this.setIcon(new ImageIcon(EMPTY));
          return this;
       * This method gets the x coordinate of Stone
       * @return the x coordinate
      public int getX()
          return this.x;
       * This method gets the y coordinate of Stone
       * @return the y coordinate
      public int getY()
          return this.y;
       * This method tests if the current Stone has been set to a color
       * @return if the Stone has been set to a color
      public boolean isOccupied()
          return (!(this.color).equals("empty"));
    }Here is the part where GameStatus calls Stone class
    public GameStatus(int size)
            this.setTitle("PENTE");
            this.setLocation(100,30);
            this.setSize(747,695);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel p = new JPanel();
            p.setLayout(new GridLayout(0, size, 0, 0));
            // initializes the array and starts inserting labels
            for (int i = 0; i < size ; i++)
                for (int j = 0; j < size ; j++)
                    array[i][j] = new infoArray(i, j, false, EMPTY);
                    Stone s = new Stone(i, j, false, EMPTY);
                    s.addMouseListener(new MousePressListener());
                    p.add(s);
            this.setResizable(false);
            this.getContentPane().add(p);
            this.setVisible(true);
            System.out.print("hello");
        }The problem is, there is only one Stone object can be shown on the JPanel.
    This is weird since it works fine when I tried to call JLabel object instead of Stone object and fill them into JPanel.
    Since Stone class extends JLabel, I just dont see why JLabel works while Stone doesn't.
    I need to know the reason badly, so I appreciate any suggestions.
    Thanks.

    Code looks reasonable. Only comment I have is that icons can be shared by multiple components. So you only need to create 3 icons, one for each state of the stone. Then you just use setIcon to change the state. No need to recreate the icon every time.

  • Painting coordinates problem

    hi,
    i have noticed that when i put a picture like a JLabel in Jpanel the coordinates for the picture start from the left upper corner meaning:
    (0,0)
    -------------->x
    |
    | picture
    |
    v
    y
    how can i rotate the coordinates so it will b that y is facing up and x remain as it is?
    thx.

    thx, but that wasn't what i meant,
    when im painting in a picture using the repaint() method,
    if for example i want to draw an oval in (0,0),
    the oval will b shown in the upper left corner of the picture but i want it to b drawn in the lower left side of the picture with the same coordinates (0,0),and 4 that i need to rotate the picture coordinates somehow,
    the g.rotate() wont help because even if i rotate i will never b able to rotate it like i want in my first post(or i could b wrong?),
    thx anyway.

  • Display priority for JLabel

    Hi.. I have a program that will be displaying a lot of JLabels with ImageIcons.
    In many cases throughout the program, JLabels will overlap or take the same coordinates as another JLabel. At any given coordinate, my intention is to give a specific JLabel priority for display over another - displaying its contents and underneath it, the other JLabel(s) would display theirs.
    I was wondering if there was some way of determining and setting which JLabel had priority for display. I noticed that by default it depends on the order in which they are added to a container. Is there another way of changing this, especially if they are already inside a container?

    In JDK1.5 and later versions I believe a new method to set the Z-order has been added.
    Prior to JDK1.5 you would need to use a JLayeredPane.

Maybe you are looking for

  • Possible to make a Newsstand App without subscription using viewer builder 1.9?

    As far as I can tell, the only way to enable newsstand through Viewer Builder 1.9 is if I select 'multi-issue with itunes subscription'. In itunes connect newsstand is enabled, but if I build the viewer with the multi-issue option selected and try to

  • How to add title/header in 3.0.1, as in previous version?

    I "upgraded" to 3.0.1-- The titles/headers of my spreadsheets would not appear in the new versions, and I see no way to add them. When I print them out, it sure is nice to know what it is (title), and how recent a version (date) it is.

  • Nested group function without group xmlagg

    I am getting nested group function without group by xmlagg when using the xmlagg function inside another xmlagg function. Find the table structure and sample data here, CREATE TABLE "TEST_TABLE"    ("KEY" NUMBER(20,0),     "NAME" VARCHAR2(50 ),     "

  • Change field for an invoicedocument item (MM)

    Hello, Is there a way (function module for instance) to change an item, in particular to change the field SGTXT (field DRSEG-SGTXT) of an invoicedocument made in MM (transaction MIRO or MIR7). For the specific group who will want to change this field

  • Join Multiple Tables

    There are two tables TBL1 and TBL2. For a SQL below: select ... from TBL1 t1, TBL2 t2 where t1.id = t2.id and t1.status='ACTIVE' and t1.city =p_city and t1.state=p_state; Will ORACLE first evaluate t1.status, t1.city, and t1.state first to eliminate