Length variable in arrays

When we use the neew operator to make an array which method is called by the new operator and the length variable in arrays resides in which class

What?

Similar Messages

  • Length variable in array

    Can anybody tell me where(class/interface/enum) is variable 'length' defined?
    In int[] intArray = {9, 99};
    System.err.println(intArray.length); Returns 2.
    Thanks

    Go throgh java.lang.reflect.Array
    It has public static Object newInstance(Class<?> componentType, int length) and public static native int getLength(Object array) getLength(Object array) is a native method, it returns lenth of the array.

  • Length of 2d arrays

    If I have this array specified:
    String[][] myArray = new String[5][10];Is there a way to use the ".length" variable to get both the "lenght" and the "width" (5 and 10) for this array? It's awefully handy with regular 1D arrays, but I'm getting a little confused with the 2D arrays.

    Sure, myArray.length is the length of the "outer"
    array. Since that outer array is just an array of
    other arrays, you take an arbitrary position, and
    find it's length.
    myArray[0].length gives the length of the first
    "inner" array. Keep in mind that all of the inner
    arrays don't necessarily have the same length.YES! Thank you! I knew there had to be some way to do this, but I couldn't figure it out.
    As it stands, the arrays I'll be working with are not ragged, so this should work quite well.
    Thanks!

  • The  in-built length variable

    The length variable we see in arrays and everywhere is built in some inbuilt class of java.. but where???? i tried to find it but cudnt get to it in any classses// tried searchin in java.lang package... can anyone tell me where the lenght variable is defined in java?????????????????
    its urgent plzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz

    If you expect clear answers, it makes sense to give clear questions.
    Well sir thanks alot... not only will i learn about java here but i guess will also get better with my language and typing which was getting destroyed because of chatting sites... anyways i understand the importance of being proffesional as just finished my engineering and now looking for a job desparately... so i hope imporving not only with java but things like proper and clear writing will help my career... thank you sir and about the link you sent me...
    I checked that and when from the src.zip folder i opened the java files.. i tired to find that length vairable.. i found a lenght variable in Array.java file in the lang package in reflect folder . but that vairable was a parameter so it that all.. i mean is that the same variable that springs up everywhere??? i mean in the explanation you sent it was written the array file has a public final lenght field but it wasn't there...hope iam clear with what excatally i want to ask.. guidance regarding this will really help me become better and answer questions in the class i go to.. thank you!!!
    here is the code i found in java file
    public static Object newInstance(Class<?> componentType, int length)
         throws NegativeArraySizeException {
         return newArray(componentType, length);
    Message was edited by:
    power-extreme

  • Select X# of variables from array at the furthest possible intervals.

    Ok, I've been working on this one for a while and I'm thinking I'm either missing something really stupidly simply because of it, or I've got my equation wrong still. 
    Basically, what I'm trying to do is select X number of items out of an array.  The only catch is, these items need to be as far apart from each other as possible.  So for example, one time I might have an array with 93 items in it which I need to grab 36 of them, evenly spaced through the array (so the first one would be the first one in the array, and the last one would be the last in the array.
    How would I go about telling the script to grab the correct array values (the most evenly spaced ones), ending up with only the X amount of output values?
    Thanks!
    dgolberg

    Hmm, this is kind of a different perspective than what I was originally thinking, but it might work.  I'll have to test it out, though it would require me running the array twice; the first time picking out the specific ones and splicing them out of the array, the second simply grabbing the remainder.
    To put it a little differently, what I was originally thinking is cycling through an array (this array's length and content varries depending on the input), and would grab the the "masters" out of the array at the set intervals (these intervals are where I'm having the most trouble), and anything it finds matching a set range for the current loop cycle that isn't considered a "master" is placed under the master as a "slave" (or essentially, a duplicate).  Below is an example of one of the loops I'm using (I have 3 nested loops in order to cycle through 3 "dimensions" of values) with my last attempt at this issue (which is only correct in certain ranges rather than all ranges like I need).
    var DF = tA.length / mNum;  //tA.length is the array length, mNum is the number of masters desired from that array.  For example, array length of 100, mNum of 75; DF = 1.333333....
    var master = 0;
    for(var z=range[1];z<range[2]+2;z=z+5) { //Cycles through the array 5 units at a time (to speed up the script)... There are 2 other loops above this using the y and z variables seen in the if statements below.
         for(var i=0;i<tA.length;i++) { //Cycles through the tempArray to find matches to the current cycle of the above loops, +/- 2
               if(tA[i][0] <= x + 2 && tA[i][0] >= x - 2 && tA[i][1] <= y + 2 && tA[i][1] >= y - 2 &&tA[i][2] <= z + 2 && tA[i][2] >= z - 2 && master < 1) { //Checks for a match, and if the master is less than 1, it sets the match as a master.
                   master = master + DF; //Adds the DF (short for Dupe Frequency) to the current master number.
                   outArray.push(tA[i]); //Set the match as a master
              } else if(tA[i][0] <= x + 2 && tA[i][0] >= x - 2 && tA[i][1] <= y + 2 && tA[i][1] >= y - 2 &&tA[i][2] <= z + 2 && tA[i][2] >= z - 2 && master >= 1) { //Checks for a match, and if the master is greater than 1, it sets a duplicate.
                   master = master - 1;
                   outArray[outArray.length-1].push(tA[i][3]); //Set the match's name as a slave under the last master
    Basically, using the code above; I need it to somehow (while cycling through the tA.length loop), figure out how often it should grab either a slave or a master (depending on which there are more of), and then the next X number of matches are either a master or a slave (again, depending on which there are more of).  So, for example, if there are 25 masters, out of 100 total items in the array, it would pick one master, the next 3 matches would be slaves, and then it would pick another master, 3 more slaves, etc. etc.  Where things start getting out of whack is when the intervals start ending up in fractions (say every 1.5 is a slave).  Obviously, you can't grab half of one, so you'd need to do a pattern more like: 1 master, 1 slave, 1 master, 2 slaves, 1 master, 1 slave; etc.
    The part I'm having trouble with is getting a working equation that knows how often to pick the (in the example above) slaves based on this varying pattern, and do so accurately regardless of the array length to master/slave ratio (the above method seems to get further off as the mNum gets closer to the tA.length).
    I guess, more than anything really, I'm just having trouble getting the math to work out right as I'm apparently using the wrong equation in my code.  If anyone has any ideas though, let me know.

  • How I can transfer data from the database into a variable (or array)?

    I made my application according to the example (http://corlan.org/2009/06/12/working-in-flash-builder-4-with-flex-and-php/). Everything works fine. I changed one function to query the database - add the two parameters and get the value of the table in String format. A test operation shows that all is ok. If I want to display this value in the text area, I simply drag and drop service to this element in the design mode
    (<s:TextArea x="153" y="435" id="nameText" text="{getDataMeanResult.lastResult[0].name}"  width="296" height="89"  />).
    It also works fine, just a warning and encouraged to use ArrayCollection.getItemAt().
    Now I want to send the value to a variable or array, but in both cases I get an error: TypeError: Error #1010: A term is undefined and has no properties..
    How can I pass a value from the database into a variable? Thank you.
    public var nameTemp:String;
    getDataMeanResult.token = authors.getDataMean(arrayOfNumber[0], dir_id);
    nameTemp = getDataMeanResult.lastResult[0].name;
    public var nameArray:Array = new Array();
    for (var i:uint=o; i<3; i++){
    getDataMeanResult.token = authors.getDataMean(arrayOfNumber[i], dir_id);
    nameArray[i] = getDataMeanResult.lastResult[0].name;
    And how i can use syntax highlighting in this forum?

    Astraport2012 wrote:
    I have to go back to the discussion. The above example works fine when i want to get a single value of the database. But i need to pass an array and get an array, because i want to get at once all the values for all pictures tooltips. I rewrote the proposed Matt PHP-script and it works. However, i can not display the resulting array.
    yep, it won't work for Arrays, you'll have to do something slightly more intelligent for them.
    easiest way would be to get your PHP to generate XML, then read that into something like an ArrayList on your HTTPService result event (depends what you're doing with it).
    for example, you could have the PHP generate XML such as:
    <pictures>
         <location>test1.png</location>
         <location>test2.png</location>
         <location>test3.png</location>
         <location>test4.png</location>
         <location>test5.png</location>
         <location>test6.png</location>
    </pictures>
    then you'll read that in as the ResultEvent, and perform something like this on it
    private var tempAC:ArrayList = new ArrayList
    protected function getStuff_resultHandler(event:ResultEvent):void
        for each(var item:Object in event.result.pictures)
           var temp:String = (item.@location).toString();
           tempAC.addItem(temp);
    in my example on cookies
    http://www.mattlefevre.com/viewExample.php?tut=flash4PHP&proj=Using%20Cookies
    you'll see an example of how to format an XML structure containing multiple values:
    if($_COOKIE["firstName"])
            print "<stored>true</stored>";
            print "<userInfo>
                    <firstName>".$_COOKIE["firstName"]."</firstName>
                    <lastName>".$_COOKIE["lastName"]."</lastName>
                    <userAge>".$_COOKIE["userAge"]."</userAge>
                    <gender>".$_COOKIE["gender"]."</gender>
                   </userInfo>";
        else
            print "<stored>false</stored>";
    which i handle like so
    if(event.result.stored == true)
                        entryPanel.title = "Welcome back " + event.result.userInfo.firstName + " " + event.result.userInfo.lastName;
                        firstName.text = event.result.userInfo.firstName;
                        lastName.text = event.result.userInfo.lastName;
                        userAge.value = event.result.userInfo.userAge;
                        userGender.selectedIndex = event.result.userInfo.gender;
    depends on what type of Array you're after
    from the sounds of it (with the mention of picture tooltips) you're trying to create a gallery with an image, and a tooltip.
    so i'd probably adopt something like
    <picture>
         <location>example1.png</location>
         <tooltip>tooltip for picture #1</tooltip>
    </picture>
    <picture>
         <location>example2.png</location>
         <tooltip>tooltip for picture #2</tooltip>
    </picture>
    <picture>
         <location>example3.png</location>
         <tooltip>tooltip for picture #3</tooltip>
    </picture>
    etc...
    or
    <picture location="example1.png" tooltip="tooltip for picture #1"/>
    <picture location="example2.png" tooltip="tooltip for picture #2"/>
    <picture location="example3.png" tooltip="tooltip for picture #3"/>
    etc...

  • How can I create a variable size array?

    How can I create a variable size array?

    ok then how can i create a new vector object?If you don't know that, you need to go back to your text book and study some more. Or read the tutorial on the basics of Java: http://java.sun.com/docs/books/tutorial/java/index.html
    After reading that you can move on to: http://java.sun.com/docs/books/tutorial/collections/index.html
    Anyway, the answer to your question is, of course:
    Vector v = new Vector();(But you should probably use ArrayList instead of Vector.)

  • Where will be the length property of Array will lie in JAVA API

    where will be the length property of Array will lie in JAVA API

    sandeepmalladi wrote:
    where will be the length property of Array will lie in JAVA APIThere is no length property of Array. As to where you find a definition of the length field of an array, it's in the [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/arrays.html].
    ~

  • Append variable and array items after a record array search

    I would like to update a variable and array item after a record array search, and wanted to know what would be the best way of carrying it out in Javascript.
    In this case, if a match is found between the variable and area item, then the postcode item should be appended to the variable.
    The same needs to be done for the array items, but I reckon that a for loop would work best in this scenario, as each individual item would need to be accessed somehow.
    Btw due to the nature of my program, there will always be a match. Furthermore, I need to be able to distinguish between the singleAddress and multipleAddresses variables.
    Hopefully this code explains things better:
    // before search
    var singleAddress = "Mount Farm";
    var multipleAddresses = ["Elfield Park", "Far Bletchley", "Medbourne", "Brickfields"];
    // this is the record which the search needs to be run against
    plot = [{
    postcode: "MK1",
    area: "Denbigh, Mount Farm",
    postcode: "MK2",
    area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
    postcode: "MK3",
    area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley",
    postcode: "MK4",
    area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill",
    postcode: "MK5",
    area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood",
    // after search is run then:
    // var singleAddress = "Mount Farm, MK1"
    // var multipleAddresses = ["Elfield Park, MK5", "Far Bletchley, MK3", "Medbourne, MK5", "Brickfields, MK2"]
    Fiddle here

    I would like to update a variable and array item after a record array search, and wanted to know what would be the best way of carrying it out in Javascript.
    In this case, if a match is found between the variable and area item, then the postcode item should be appended to the variable.
    The same needs to be done for the array items, but I reckon that a for loop would work best in this scenario, as each individual item would need to be accessed somehow.
    Btw due to the nature of my program, there will always be a match. Furthermore, I need to be able to distinguish between the singleAddress and multipleAddresses variables.
    Hopefully this code explains things better:
    // before search
    var singleAddress = "Mount Farm";
    var multipleAddresses = ["Elfield Park", "Far Bletchley", "Medbourne", "Brickfields"];
    // this is the record which the search needs to be run against
    plot = [{
    postcode: "MK1",
    area: "Denbigh, Mount Farm",
    postcode: "MK2",
    area: "Brickfields, Central Bletchley, Fenny Stratford, Water Eaton"
    postcode: "MK3",
    area: "Church Green, Far Bletchley, Old Bletchley, West Bletchley",
    postcode: "MK4",
    area: "Emerson Valley, Furzton, Kingsmead, Shenley Brook End, Snelshall West, Tattenhoe, Tattenhoe Park, Westcroft, Whaddon, Woodhill",
    postcode: "MK5",
    area: "Crownhill, Elfield Park, Grange Farm, Oakhill, Knowlhill, Loughton, Medbourne, Shenley Brook End, Shenley Church End, Shenley Lodge, Shenley Wood",
    // after search is run then:
    // var singleAddress = "Mount Farm, MK1"
    // var multipleAddresses = ["Elfield Park, MK5", "Far Bletchley, MK3", "Medbourne, MK5", "Brickfields, MK2"]
    Fiddle here

  • Länge eines Array (length of an array)

    Hallo,
    gibt es ähnlich wie bei Kanälen - chnlength - eine Möglichkeit die Länge von Arrays abzufragen?
    Is there any possibility to get the length of an array like chnlength?
    Gruß

    Arrays in vbs are a little tricky.
    Thats mainly because
    dim arr()
    does not create an empty array but an unitialized one. So calling Ubound(arr) will raise an error.
    It will also fail to loop using "for each".
    So I would suggest to never use "()" to define an array but
    dim arr : arr = Array()
    MsgBox "length=" & ubound(arr) + 1
    dim arrElem
    for each arrElem in arr
    ' here we can do something
    Next
    Array() will create an initialized Array of length 0. UBound will give -1 as return value.
    Usng this returing an array from a funtion works quiet well without having to check for exceptions if array is empty.
    Option Explicit
    Function GetElems()
    GetElems = Array()
    ' do some stuff
    end function
    dim elems : elems = GetElems
    dim elem
    for each elem in elems
    ' here we can do something
    Next
    If you want to dynamically grow an array you can use redim preserve.
    Option Explicit
    dim arr : arr = Array()
    redim preserve arr(Ubound(arr) + 1)
    arr(UBound(arr)) = "Appended text"
    MsgBox "length=" & ubound(arr) + 1 & VBCRLF & arr(0)

  • Variable to array

    I have variable, abc; whose value is in the format val1,val2,val3,..
    I want to convert it into an array, like that arr[0]=val1; arr[1]=val2; so on. How can I do this?
    Usman

    examine this class that I did
    import java.lang.*;
    public class ReadString {
    public static void main(String[] args){
    String abc = "1,2,3,4,5,6";
    StringBuffer abc2 = new StringBuffer(abc);
    int arrayLength = abc2.length(); //get length
    int[] abcFinal = new int[6];
    for (int i=0; i<arrayLength; i++) { //test characters
    int anIndex;
    if (!(abc2.substring(i,i+1)).equals(",")) { //if it is a number
    //(i/2) is ta little formula to be able to assign the
    //right index in the intArray to the number
    anIndex = (i/2);
    //set value to array
    abcFinal[anIndex] = Integer.parseInt(abc2.substring(i,i+1));
    for (int j=0;j<abcFinal.length;j++ ) {
    System.out.println("i = " + j + " value = " + abcFinal[j]);
    }//end main
    }//end class

  • Variable size array of checkboxes

    I am new to weblogic. I am using weblogic 8.1 SP3.
    My problem is that i have to display a table with first coloumn of each row a name and rest coloumns should contain checkboxes. Each row has same number of checkboxes. But the number of checkboxes in each row everytime page is loaded is variable.
    If anyone can tell me how to do this and how to bind data to form bean. I tried using a repeater tag with a Boolean array but of no use.
    Thanks in advance
    Akshay

    Please create a new default application and drop the checkbox folder into
    the web project and run the jpf.
    Thanks
    Vimala
    <Vimala Ranganathan> wrote in message news:[email protected]..
    Hi Akshay
    I have attached a sample that will show a page that will take in the
    number of checkboxes the page will have (like you can get this as request
    attribute, req parameter etc) and displays the page using repeater tag.
    Steps:
    Unzip the file and open with workshop IDE
    Build and run the jpf in the folder checkbox
    I am not sure how to attach the file. Can you please let me know your
    email so I can send it to you?
    Thanks
    Vimala

  • Variable size array output from dynamic dispatch class method on FPGA

    I have a Parent class on the FPGA that will serve as a template/framework for future code that will be developed. I had planned on creating a child class and overriding a couple methods. The child class constant would be dropped on the block diagram so the compiler wouldn't have any trouble figuring out which method (parent's or child's) should be used (i.e. the parent's method will never actually be used and won't be compiled with the main code). The output of one of the methods is an array. This array will have a different size depending on the application. I defined the array size as variable. In the child method, there is no question about the size of the array so the compiler should be able to figure it out. However, when I try to compile, I get an error about the array size. I can't figure out any way around it. Any thought would be greatly appreciated! 
    Thanks, Patrick
    Solved!
    Go to Solution.
    Attachments:
    FPGA Test.zip ‏1194 KB

    Wait what?
    Can we use dynamic dispatch VIs on FPGA?  Really?  I was completely unaware of this.  Obviously the dependencies need to be constant and known at compile time but...... This would have saved me a lot of headaches in the last few months.
    Since which LV version is this supported?
    Say hello to my little friend.
    RFC 2323 FHE-Compliant

  • Variable size array in a FlowPane

    If i have an array of variable size (for example a array of cards).
    How can i build something to show the elements(in a FlowPane for example) and each of them having its own controller (fxml + controller for each card), so the container (flow pane) of the elements (cards) can have it's elements swaped, removed or added new ones?
    Controller:
    public class HandController extends FlowPane implements Initializable{
        @Override public void initialize(URL arg0, ResourceBundle arg1){
        public void setHand(ArrayList<Cards> Hand){
            //this would work if the hand were static
            for(int i = 0; i < Hand.size(); ++i){
                FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("CardView.fxml"));
                CardController controller = new CardController();
                fxmlLoader.setController(controller);
                fxmlLoader.setRoot(controller);
                Parent card = (Parent)fxmlLoader.load();
                fxmlLoader.setRoot(card);
                this.getChildren().add(card);
                controller.setCard(Hand.get(i));
    }Fxml:
    <fx:root type="FlowPane" xmlns:fx="http://javafx.com/fxml"
             stylesheets="view/Style.css">
        <children>
            <!--should i put something here?-->
        </children>
    </fx:root>

    Well, I was bored...
    This "game" has a hand of up to five cards. You can deal from a deck to the hand, and then play (or discard) a card by double-clicking on it.
    The model comprises a Card class, a Deck class, and a GameModel class. The last one tracks the hand and deck and the relationship between them. Card and Deck were written from my memory of reading an example of using Enums by Josh Bloch.
    Card.java
    package cardgame;
    public class Card {
         public enum Rank {
              Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King
         public enum Suit {
              Clubs, Diamonds, Hearts, Spades
         private final Rank rank;
         private final Suit suit;
         public Card(Rank rank, Suit suit) {
              this.rank = rank;
              this.suit = suit;
         public Rank getRank() {
              return rank;
         public Suit getSuit() {
              return suit;
         @Override
         public String toString() {
              return String.format("%s of %s", rank, suit);
         @Override
         public int hashCode() {
              final int prime = 31;
              int result = 1;
              result = prime * result + ((rank == null) ? 0 : rank.hashCode());
              result = prime * result + ((suit == null) ? 0 : suit.hashCode());
              return result;
         @Override
         public boolean equals(Object obj) {
              if (this == obj)
                   return true;
              if (obj == null)
                   return false;
              if (getClass() != obj.getClass())
                   return false;
              Card other = (Card) obj;
              if (rank != other.rank)
                   return false;
              if (suit != other.suit)
                   return false;
              return true;
    }Deck.java
    package cardgame;
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Random;
    import cardgame.Card.Rank;
    import cardgame.Card.Suit;
    public class Deck {
         private final List<Card> cards;
         private Deck() {
              cards = new LinkedList<Card>();
              for (Suit suit : Suit.values())
                   for (Rank rank : Rank.values())
                        cards.add(new Card(rank, suit));
         public static Deck newDeck() {
              return new Deck();
         public static Deck shuffledDeck() {
              return newDeck().shuffle();
         public Deck shuffle() {
              final List<Card> copy = new ArrayList<Card>(cards.size());
              Random rng = new Random();
              while (cards.size() > 0) {
                   int index = rng.nextInt(cards.size());
                   copy.add(cards.remove(index));
              cards.clear();
              cards.addAll(copy);
              return this;
         public Card deal() {
              return cards.remove(0);
         public int size() {
              return cards.size();
    }GameModel.java
    package cardgame;
    import javafx.beans.binding.BooleanBinding;
    import javafx.beans.property.BooleanProperty;
    import javafx.beans.property.ReadOnlyBooleanProperty;
    import javafx.beans.property.SimpleBooleanProperty;
    import javafx.collections.FXCollections;
    import javafx.collections.ObservableList;
    public class GameModel {
         private ObservableList<Card> hand;
         private Deck deck;
         private BooleanProperty canDeal;
         public GameModel() {
              this.hand = FXCollections.observableArrayList();
              this.deck = Deck.newDeck().shuffle();
              this.canDeal = new SimpleBooleanProperty(this, "canDeal");
              canDeal.bind(new BooleanBinding() {
                        super.bind(hand);
                   @Override
                   protected boolean computeValue() {
                        return deck.size() > 0 && hand.size() < 5;
         public ObservableList<Card> getHand() {
              return hand;
         public ReadOnlyBooleanProperty canDealProperty() {
              return canDeal;
         public boolean canDeal() {
              return canDeal.get();
         public void deal() throws IllegalStateException {
              if (deck.size() <= 0) {
                   throw new IllegalStateException("No cards left to deal");
              if (hand.size() >= 5) {
                   throw new IllegalStateException("Hand is full");
              hand.add(deck.deal());
         public void playCard(Card card) throws IllegalStateException {
              if (hand.contains(card)) {
                   hand.remove(card);
              } else {
                   throw new IllegalStateException("Hand does not contain " + card);
    }The CardController is the controller for a CardView. It takes a reference to a Card and its initialize method initializes the view to display it (the view is just a simple label).
    CardController.java
    package cardgame;
    import javafx.fxml.FXML;
    import javafx.scene.control.Label;
    public class CardController {
         private final Card card;
         @FXML
         private Label label;
         public CardController(Card card) {
              this.card = card;
         public void initialize() {
              label.setText(String.format("%s%nof%n%s", card.getRank(),
                        card.getSuit()));
    }The HandController is the controller for the display of the hand. This is where most of the action happens. The trick here is that it requires a reference to a GameModel, which needs to be injected from somewhere, so we need a setModel(...) method, or something similar. I didn't want to assume the order of events: i.e. whether the model is injected before or after the initialize() method is invoked. To keep this flexibility, I used an ObjectProperty to wrap the model, and listen for changes to it. When the model is updated, I register a listener with the hand (exposed by the model). This listener in turn rebuilds the views of the cards when the hand changes. There's also a "deal" button, whose disabled state is managed by binding to a property in the model (using a neat trick from the Bindings class to allow the model value to be dynamic).
    HandController.java
    package cardgame;
    import java.io.IOException;
    import javafx.beans.binding.Bindings;
    import javafx.beans.property.ObjectProperty;
    import javafx.beans.property.SimpleObjectProperty;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.collections.ListChangeListener;
    import javafx.event.EventHandler;
    import javafx.fxml.FXML;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Node;
    import javafx.scene.control.Button;
    import javafx.scene.input.MouseEvent;
    import javafx.scene.layout.Pane;
    public class HandController {
         private ObjectProperty<GameModel> model;
         @FXML
         private Pane container;
         @FXML
         private Button dealButton;
         public HandController() {
              this.model = new SimpleObjectProperty<GameModel>(this, "model", null);
              final ListChangeListener<Card> handListener = new ListChangeListener<Card>() {
                   @Override
                   public void onChanged(Change<? extends Card> change) {
                        container.getChildren().clear();
                        try {
                             for (Card card : model.get().getHand()) {
                                  container.getChildren().add(loadCardView(card));
                        } catch (IOException e) {
                             e.printStackTrace();
              model.addListener(new ChangeListener<GameModel>() {
                   @Override
                   public void changed(
                             ObservableValue<? extends GameModel> observable,
                             GameModel oldValue, GameModel newValue) {
                        if (oldValue != null) {
                             oldValue.getHand().removeListener(handListener);
                        if (newValue != null) {
                             newValue.getHand().addListener(handListener);
         public void setModel(GameModel model) {
              this.model.set(model);
         public void initialize() {
              dealButton.disableProperty().bind(
                        Bindings.selectBoolean(model, "canDeal").not());
         private Node loadCardView(final Card card) throws IOException {
              FXMLLoader loader = new FXMLLoader(getClass().getResource(
                        "CardView.fxml"));
              CardController controller = new CardController(card);
              loader.setController(controller);
              Node cardView = (Node) loader.load();
              cardView.setOnMouseClicked(new EventHandler<MouseEvent>() {
                   @Override
                   public void handle(MouseEvent event) {
                        if (event.getClickCount() == 2) {
                             model.get().playCard(card);
              return cardView;
         public void dealCard() {
              model.get().deal();
    }Here are the FXML files:
    CardView.fxml
    <?xml version="1.0" encoding="UTF-8"?>
    <?import javafx.scene.layout.StackPane?>
    <?import javafx.scene.control.Label?>
    <?import java.lang.String?>
    <StackPane xmlns:fx="http://javafx.com/fxml" prefHeight="150" prefWidth="80" minWidth="80" maxWidth="80" minHeight="150" maxHeight="150">
         <Label fx:id="label" >
         </Label>
         <styleClass>
              <String fx:value="card"/>
         </styleClass>
    </StackPane>Hand.fxml
    <?xml version="1.0" encoding="UTF-8"?>
    <?import javafx.scene.layout.FlowPane?>
    <?import javafx.scene.layout.BorderPane?>
    <?import javafx.scene.control.Button?>
    <?import javafx.scene.control.ScrollPane?>
    <?import java.lang.String?>
    <BorderPane xmlns:fx="http://javafx.com/fxml" fx:controller="cardgame.HandController" >
         <center>
              <FlowPane hgap="5" vgap="10" fx:id="container">
              </FlowPane>
         </center>
         <bottom>
              <Button text="Deal" onAction="#dealCard" fx:id="dealButton"/>
         </bottom>
    </BorderPane>The overall application is managed by a Game.fxml:
    <?xml version="1.0" encoding="UTF-8"?>
    <?import javafx.scene.layout.BorderPane?>
    <BorderPane xmlns:fx="http://javafx.com/fxml" fx:controller="cardgame.GameController">
         <center>
              <fx:include source="Hand.fxml" fx:id="hand" />
         </center>
    </BorderPane>with a GameController:
    package cardgame;
    import javafx.fxml.FXML;
    public class GameController {
         @FXML private HandController handController ;
         private GameModel model ;
         public GameController() {
              model = new GameModel();
         public void initialize() {
              handController.setModel(model);
    }Game.java is the main class:
    package cardgame;
    import java.io.IOException;
    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.scene.paint.Color;
    import javafx.stage.Stage;
    public class Game extends Application {
         @Override
         public void start(Stage primaryStage) throws IOException {
              Scene scene = new Scene(FXMLLoader.<Parent>load(getClass().getResource("Game.fxml")), 600, 400, Color.DARKGREEN);
              scene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
              primaryStage.setScene(scene);
              primaryStage.show();
         public static void main(String[] args) {
              launch(args);
    }and then a style sheet
    style.css:
    @CHARSET "US-ASCII";
    .card {
         -fx-background-color: white ;
         -fx-border-color: black ;
         -fx-border-radius: 5 ;
         -fx-border-style: solid ;
         -fx-padding: 5 ;
    .card .label {
         -fx-text-alignment: center ;
    }

  • How can I know the length of an array in the class?

    hard to express, I show guys an example:)
    public class code{
    pblic String[] str; // String array
    public test () {
    // I hope to print all items in the array after initiation;
    // e.g. if String[3] , then print str0, str1,str2; if String[4], then //print str0, str1, str2, str3;
    My puzzle here is, since the "str" may be not the same length in different initiation of code object, how can I implement the test method to print all items

    for (int i = 0; i < str.length; i++)
      System.out.println(str);

Maybe you are looking for