• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 253
  • Last Modified:

click event

i have an array of JLabel and i have arranged them like
1 2 3
4 5 6
7 8 9

and added .addmouselistener to them but am not sure how to make it so that when i click 2 it will be not do anything and after clicking 2, i clicked 1 they will swap. its like picking 2 jlabel and checking if they can be swapped and if yes, then swap and if no pick another 2.

also how can i get the n in jlabel[n] if its been clicked.
0
teamasia
Asked:
teamasia
  • 13
  • 9
  • 7
  • +1
2 Solutions
 
TimYatesCommented:
Store a variable like:

   JLabel clicked = null ;

in your main class (that adds all the labels)

Then, when you get a click event;

  if( clicked == null )
    clicked = (JLabel)event.getSource() ;
  else
  {
    swap( (JLabel)event.getSource(), clicked ) ;
    clicked = null ;
  }

(where the "swap" method will do your swapping :-)
0
 
girionisCommented:
What I would do is to have an instance variable that is set every time a button is clicked. Then check this variable if it is an even number. If it is then set the text repsectively (instead of chaning labels location).
0
 
TimYatesCommented:
girionis' method is much easier (as your "swap" method will just be swappnig two strings, rather than rebuilding and revalidating your component)...
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
teamasiaAuthor Commented:
ok so can anyone tell me how get the n in label[n]. i also need to get the n. thankx
0
 
TimYatesCommented:
public in whichLabel( JLabel source, JLabel[] array )
{
    for( int i = 0 ; i < array.length ; i++ )
        if( array[ i ] == source )
            return i ;
    return -1 ;
}
0
 
Giant2Commented:
Take the label text (it contains 1..9).
0
 
teamasiaAuthor Commented:
giant2, when it is swapped it will change text value
0
 
Giant2Commented:
I explain.
If your label contains the number position you can do something like this:


public int returnPosition(JLabel source){
try{
return new Integer(source.getText()).intValue();
}catch (Exception ex){}
return -1;
}

Giant.
0
 
Giant2Commented:
>when it is swapped it will change text value

Ok, so the TimYates method is usefull.
(P.S. the correct declaration is:
publiclic int which...)
0
 
teamasiaAuthor Commented:
timyates. isnt there any other way. my jlabel is made up of 3 1s 3 0s and 3 2s so if i do that wont it make it wrong. thankx sorry i didnt say this earlier
0
 
girionisCommented:
Simply getting the reference wouldbe enough.
0
 
teamasiaAuthor Commented:
can i get a sample pls girionis
0
 
Giant2Commented:
What do you mean with:
>my jlabel is made up of 3 1s 3 0s and 3 2s
??
0
 
teamasiaAuthor Commented:
1 1 1
0 0 0
2 2 2
0
 
TimYatesCommented:
you really don't need to know the index...or you shouldn't...

what code do you have now?

Can you post it here?
0
 
teamasiaAuthor Commented:
its a server client game im making. so i was thinking of sending the index of that jlabel so that the server can track the changes. if anyone got any better idea how to do this pls
0
 
Giant2Commented:
But your representation is a 2 dimensional array, or 1 dimensional array?
array[][]
or
array[]
??
0
 
girionisCommented:
This shoould do what you are looking for:

import java.awt.GridLayout;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import java.awt.event.*;

/*
 * LabelDemo.java is a 1.4 application that needs one other file:
 *   images/middle.gif
 */
public class LabelDemo extends JPanel implements MouseListener
{
      private int swap = 0;
      JLabel label1, label2, label3;
      JLabel [] labels = {label1, label2, label3};
      JLabel temp = null;
      
    public LabelDemo() {
        super(new GridLayout(3,1));  //3 rows, 1 column
       

        ImageIcon icon = createImageIcon("images/middle.gif",
                                         "a pretty but meaningless splat");
            
        //Create the first label.
        labels[0] = new JLabel("Image and Text",
                            icon,
                            JLabel.CENTER);
        //Set the position of its text, relative to its icon:
        labels[0].setVerticalTextPosition(JLabel.BOTTOM);
        labels[0].setHorizontalTextPosition(JLabel.CENTER);

        //Create the other labels.
        labels[1] = new JLabel("Text-Only Label");
        labels[2] = new JLabel("another one");

        //Create tool tips, for the heck of it.
        labels[0].setToolTipText("A label containing both image and text");
        labels[1].setToolTipText("A label containing only text");
        labels[2].setToolTipText("A label containing only an image");

        //Add the labels.
        add(labels[0]);
        add(labels[1]);
        add(labels[2]);
            
            for (int i=0; i<labels.length; i++)
            {
                  labels[i].addMouseListener(this);
            }
    }

      
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path,
                                               String description) {
        java.net.URL imgURL = LabelDemo.class.getResource(path);
        if (imgURL != null) {
            return new ImageIcon(imgURL, description);
        } else {
            System.err.println("Couldn't find file: " + path);
            return null;
        }
    }

    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        //Make sure we have nice window decorations.
        JFrame.setDefaultLookAndFeelDecorated(true);

        //Create and set up the window.
        JFrame frame = new JFrame("LabelDemo");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        //Create and set up the content pane.
        LabelDemo newContentPane = new LabelDemo();
        newContentPane.setOpaque(true); //content panes must be opaque
        frame.setContentPane(newContentPane);

        //Display the window.
        frame.pack();
        frame.setVisible(true);
    }

      public void mousePressed(MouseEvent e) {}
      public void mouseClicked(MouseEvent e)
      {
            swap++;
            if (swap % 2 == 0)
            {
                  String text = temp.getText();
                  temp.setText(((JLabel) e.getSource()).getText());
                  ((JLabel) e.getSource()).setText(text);
                  
            }
            temp = (JLabel) e.getSource();
            
            JLabel lbl = (JLabel) e.getSource();
            System.out.println(lbl.getText());
      }
      
      public void mouseReleased(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}
      
    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();
            }
        });
    }
}
0
 
teamasiaAuthor Commented:
just 1 dimensional array
0
 
Giant2Commented:
client:
swap position 5 to position 3 and send this message to the server
then change the local representation of the game


server:
receive the message and change it's representation of the game (eventually save the log)

A better way is to send an Ok message to the client so that the client could change its local representation (for allineation).
0
 
girionisCommented:
If you have icons on the labels instead of text simply replace the set/getText() methods with set/getIcon() methods.
0
 
teamasiaAuthor Commented:
giant2, i know how to do that but to be able to do that i need the index of the jlabel which i am asking
0
 
girionisCommented:
> its a server client game im making. so i was thinking of sending the index of that jlabel so
>that the server can track the changes. if anyone got any better idea how to do this pls

You could do that too, or you could replicate the labels on the other side and just send the reference of the label, so the other side knows which one to change.
0
 
girionisCommented:
> but to be able to do that i need the index of the jlabel which i am asking

Look at Tim's code, it should get you the index.
0
 
Giant2Commented:
>i know how to do that but to be able to do that i need the index of the jlabel which i am asking

Like I told before.
The TimYates code goes Ok (substitue public in with public int) to do this.
0
 
TimYatesCommented:
> (substitue public in with public int)

Whoops :-)
0
 
teamasiaAuthor Commented:
      for (int i = 0; i < board.length; i++){
           board[i] = new JLabel("" + i);
           board[i].addMouseListener(
                new MouseAdapter(){
                    public void mouseClicked(MouseEvent e) {
                        if (templabel == null){
                            templabel = (JLabel)e.getSource();
                            temp = templabel.getText();
                            System.out.println("Temp is now: " + temp);
                        }
                        else{
                           templabel = (JLabel)e.getSource();
                           templabel = null;
                        }
                    }

why does the first click item doesnt change?
                }
           );
0
 
teamasiaAuthor Commented:
ah bah sorry i get it now hehe
0
 
girionisCommented:
teamasia have you tried my code? It does what you asked for.
0
 
teamasiaAuthor Commented:
yes i get the index now thank you.
0
 
girionisCommented:
I am not using any index, just the label reference.
0
 
teamasiaAuthor Commented:
ah thank you all. i get it now. i will split the points thankx!
0
 
teamasiaAuthor Commented:
Thank you all!
0
 
TimYatesCommented:
:-)

Good luck!!

Tim
0
 
girionisCommented:
:)
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

  • 13
  • 9
  • 7
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now