Solved

click event

Posted on 2004-08-24
35
209 Views
Last Modified: 2010-03-31
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
Comment
Question by:teamasia
  • 13
  • 9
  • 7
  • +1
35 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 11879672
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
 
LVL 35

Expert Comment

by:girionis
ID: 11879677
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
 
LVL 35

Expert Comment

by:TimYates
ID: 11879701
girionis' method is much easier (as your "swap" method will just be swappnig two strings, rather than rebuilding and revalidating your component)...
0
 

Author Comment

by:teamasia
ID: 11879736
ok so can anyone tell me how get the n in label[n]. i also need to get the n. thankx
0
 
LVL 35

Assisted Solution

by:TimYates
TimYates earned 250 total points
ID: 11879744
public in whichLabel( JLabel source, JLabel[] array )
{
    for( int i = 0 ; i < array.length ; i++ )
        if( array[ i ] == source )
            return i ;
    return -1 ;
}
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11879747
Take the label text (it contains 1..9).
0
 

Author Comment

by:teamasia
ID: 11879754
giant2, when it is swapped it will change text value
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11879759
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
 
LVL 12

Expert Comment

by:Giant2
ID: 11879766
>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
 

Author Comment

by:teamasia
ID: 11879768
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
 
LVL 35

Expert Comment

by:girionis
ID: 11879769
Simply getting the reference wouldbe enough.
0
 

Author Comment

by:teamasia
ID: 11879773
can i get a sample pls girionis
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11879776
What do you mean with:
>my jlabel is made up of 3 1s 3 0s and 3 2s
??
0
 

Author Comment

by:teamasia
ID: 11879778
1 1 1
0 0 0
2 2 2
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11879781
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
 

Author Comment

by:teamasia
ID: 11879793
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
 
LVL 12

Expert Comment

by:Giant2
ID: 11879799
But your representation is a 2 dimensional array, or 1 dimensional array?
array[][]
or
array[]
??
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 35

Accepted Solution

by:
girionis earned 250 total points
ID: 11879804
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
 

Author Comment

by:teamasia
ID: 11879814
just 1 dimensional array
0
 
LVL 12

Expert Comment

by:Giant2
ID: 11879818
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
 
LVL 35

Expert Comment

by:girionis
ID: 11879824
If you have icons on the labels instead of text simply replace the set/getText() methods with set/getIcon() methods.
0
 

Author Comment

by:teamasia
ID: 11879831
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
 
LVL 35

Expert Comment

by:girionis
ID: 11879836
> 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
 
LVL 35

Expert Comment

by:girionis
ID: 11879847
> 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
 
LVL 12

Expert Comment

by:Giant2
ID: 11879878
>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
 
LVL 35

Expert Comment

by:TimYates
ID: 11879904
> (substitue public in with public int)

Whoops :-)
0
 

Author Comment

by:teamasia
ID: 11879927
      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
 

Author Comment

by:teamasia
ID: 11879940
ah bah sorry i get it now hehe
0
 
LVL 35

Expert Comment

by:girionis
ID: 11879951
teamasia have you tried my code? It does what you asked for.
0
 

Author Comment

by:teamasia
ID: 11879963
yes i get the index now thank you.
0
 
LVL 35

Expert Comment

by:girionis
ID: 11879990
I am not using any index, just the label reference.
0
 

Author Comment

by:teamasia
ID: 11880003
ah thank you all. i get it now. i will split the points thankx!
0
 

Author Comment

by:teamasia
ID: 11880018
Thank you all!
0
 
LVL 35

Expert Comment

by:TimYates
ID: 11880087
:-)

Good luck!!

Tim
0
 
LVL 35

Expert Comment

by:girionis
ID: 11880100
:)
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

For customizing the look of your lightweight component and making it look opaque like it was made of plastic.  This tip assumes your component to be of rectangular shape and completely opaque.   (CODE)
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …

707 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now