Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / GUI / August 2004

Tip: Looking for answers? Try searching our database.

putClientProperty

Thread view: 
Alessandro Mizzoni - 29 Aug 2004 02:51 GMT
HI, i have this two funcion: i want put on the client property of "pulsante"
the array "m". How can I put the array?

pulsante.putClientProperty(PROP_ARRAY, ????????????);<=============

and how can i get in a int[][] the array "m" in the ActionListener?

int[][] array=  ((int[][])
pressedButton.getClientProperty(PROP_ARRAY)).intValue();  <=====?????

thx!!!!

private void CreateRamdom (int[][] m){
JPanel pannello = new JPanel();
pannello.setLayout(new GridLayout(N, N));
   Random generator = new Random();

    for (int i = 0; i < N; i++)
      for (int j = 0; j < N; j++)
        mat[i][j] = generator.nextInt(MAXELEM);

    for (int i = 0; i < N; i++)
      for (int j = 0; j < N; j++)
      {
        JButton pulsante = new JButton(Integer.toString(mat[i][j]));
        jb[i][j] = pulsante;
        // XXX pulsante.addMouseListener(leftListener);

        // Set row and col index of the button; used by buttonListener
        pulsante.putClientProperty(PROP_MAT_ROW, new Integer(i));
        pulsante.putClientProperty(PROP_MAT_COL, new Integer(j));
        pulsante.putClientProperty(PROP_ARRAY, int[N][N](m));

        // Add buttonListener as ActionListener
        pulsante.addActionListener(buttonListener);
      }

     for (int i = 0; i < jb.length; i++)
             for (int j = 0; j < N; j++)
                    pannello.add(jb[i][j]);
                       getContentPane().add(pannello, BorderLayout.CENTER);
     }

private ActionListener buttonListener = new ActionListener()
  {
    public void actionPerformed(ActionEvent e)
    {
      JButton pressedButton = (JButton) e.getSource();

      // Get row and column index from the button
      int row =
        ((Integer)
pressedButton.getClientProperty(PROP_MAT_ROW)).intValue();
      int col =
        ((Integer)
pressedButton.getClientProperty(PROP_MAT_COL)).intValue();

      // matrix value
      int value = mat[row][col];

      String input =
        JOptionPane.showInputDialog(
          QuadratoFrame.this,
          "Inserisci un nuovo valore:",
          Integer.toString(value));
      if (input != null)
      {
        // input != null: user did not cancel the dialog
        try
        {
          // Parse input to see if it contains a valid integer;
          // if it doesn't, parseInt throws a NumberFormatException.
          // Trim input to remove leading and trailing spaces
          value = Integer.parseInt(input.trim());

          // Test if value is in the appropriate range
          if (value >= 0 && value < MAXELEM)
          {
            // Yep: change matrix...
            mat[row][col] = value;
            // ...and the text of the button
            pressedButton.setText(Integer.toString(value));
          }
          else
          {
            // Value was not in the range
            throw new NumberFormatException(
              "value must be >= 0 and < " + MAXELEM);
          }
        }
        catch (NumberFormatException ex)
        {
          // Input was invalid: show error dialog
          JOptionPane.showMessageDialog(
            QuadratoFrame.this,
            "Valore inserito: " + input + "\n" + ex.getMessage(),
            "hai inserito un valore non valido, inserire un intero",
            JOptionPane.ERROR_MESSAGE);
        }
      }
    }
  };
zoopy - 29 Aug 2004 16:35 GMT
> HI, i have this two funcion: i want put on the client property of "pulsante"
> the array "m". How can I put the array?
>
> pulsante.putClientProperty(PROP_ARRAY, ????????????);<=============

Assuming m is correctly declared as an array (I didn't read your code
thoroughly), use

    pulsante.putClientProperty(PROP_ARRAY, m);

Some additional explanation, because, please don't be offended, I see
that you're struggling with Java's concepts of objects and primitives.
If you want to read more about them, you could go to
<http://java.sun.com/docs/books/tutorial/java/index.html>

The method putClientProperty requires to parameters of type Object (see
<http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComponent.html#putClientPro
perty(java.lang.Object,%20java.lang.Object
)>).
Assuming PROP_ARRAY is a String, and class String is a subclass of
Object, so the first parameter is OK.
In Java, an array is considered to be an object (e.g. a String[], a
JButton[][], even arrays of primitive types, like double[], int[][]).
Assuming 'm' is an array, the second parameter is OK too.

In your program, you also store column and row indices. Java primitive
types (int, double, etc., all with lowercase) aren't objects, and
therefore the following does not work (you'll get a compile time error):
    int i = 2;
    pulsante.putClientProperty(PROP_MAT_ROW, i);
Yet, to be able to store a primitive, you wrap it in an instance of its
correspinding wrapper class (int->Integer, double->Double,
char->Character, etc.) (*). So you write the following (as you already
have) in your code:
    pulsante.putClientProperty(PROP_MAT_ROW, new Integer(i));

(*)In the upcoming Java version 5, the compiler will do this for you
automatically (auto-boxing its called).

> and how can i get in a int[][] the array "m" in the ActionListener?
>
> int[][] array=  ((int[][])
> pressedButton.getClientProperty(PROP_ARRAY)).intValue();  <=====?????

int[][] array = (int[][]) pressedButton.getClientProperty(PROP_ARRAY);

The method getClientProperty(someKey) returns a Object (see
<http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JComponent.html#getClientPro
perty(java.lang.Object
)>).
If you want to assign it to a variable 'array' of type int[][], you need
to cast (convert) the Object to int[][], otherwise the compiler will not
be happy and show you error messages that you probably already have
seen. This is what the '(int[][])' means: cast to the type between the ().
When on runtime the actual type of the object returned by
getClientProperty is not int[][], the cast to int[][] fails and you will
see a ClassCastException during the excution of the program.

So, just to check for you: is 'm', the object stored with
putClientProperty, declared of type int[][]?

For the row and column indices, you do a similar thing. The row index
was stored as an Integer object (the primitive int wrapped in a Object),
so you cast it to an Integer:

   Integer rowIndex = (Integer)
                      pressedButton.getClientProperty(PROP_MAT_ROW);

However, rowIndex is an object, an instance of the class Integer. To get
the primitive int back, the class Integer provides the method
intValue(): it returns the int that was wrapped inside. See
<http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html#intValue()>

   Integer rowIndex = (Integer)
                      pressedButton.getClientProperty(PROP_MAT_ROW);
   int row = rowIndex.intValue();

These two statements can be combined to a single statement:

   int row = ( (Integer)
               pressedButton.getClientProperty(PROP_MAT_ROW);
             ).intValue();

Signature

Regards,
Z.



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.