Override fxml Controller instantiation

Hi everyone,
I want to integrate my DI solution with the FXML, I found some solutions on web that add the injected controller instance on the nameSpace of FXMLLoader for each file. But that's not work with fx:include...
I'de like know if there's another solutions... like override the default controller builder or something like that...
thanks,
best regards.

Yes, this is supported in JavaFX 2.1. See FXMLLoader#setControllerFactory().

Similar Messages

  • Integration between initializable & constructor in a FXML controller class

    Hi guys!
    I know how to create a create an object from an fxml file in two ways:
    1 - (fxml + controller) => no constructor, initialize method create the object
    2 - (fxml without controller + a class with a constructor that become his controller once instantiated) => the object must be instantiated by the constructor, no initialize method
    is there any way to create a single controller with both the approaches ?
    i'm trying but it constructor and initialize seems to call each other, ending in a StackOverflowError...
    suggestions?

    Solved it by myself.
    Access the root element of the FXML file by giving it a fx:id and inject it into the controller by using the @FXML annotation:
    @FXML
    private BorderPane borderPane; // this is my root element in FXML (fx:id="borderPane")
    @FXML
    protected void handleMenuItemImportCsvAction(final ActionEvent event) {
        final FileChooser fileChooser = new FileChooser();
        final File importFile = fileChooser.showOpenDialog(borderPane.getScene().getWindow());
    }

  • Pass controller name runtime

    Hi,
    I want to develope reusable FXML components. I want to pass controller name runtime to FXML, so that everyone can write down own controller and pass the attributes to FXML.
    e.g.
    I will have AnchorPane.FXML. Button should contain <fx:define> component for controller name
    So that
    <AnchorPane id="AnchorPane" xmlns:fx="http://javafx.com/fxml" fx:controller="*+_XXXXXXXXXX_+*" >
    This can be included in some XXX.FXML, but XXXXXXXXXX should be passed throgh <var name="controller" value="${controller}"/>, so that button properties like name,size can be passed using own controller.
    Is there any way I can do so?
    Thanks in advance.

    I want to develope reusable FXML components. I want to pass controller name runtime to FXML, so that everyone can write down own controller and pass the attributes to FXML.This isn't currently possible. However, in JavaFX 2.1, you can provide a custom controller factory implementation to FXMLLoader that will allow your application to manage the controller instantiation process. Maybe this will help you address your use case.
    XXXXXXXXXX should be passed throgh <var name="controller" value="${controller}"/>, so that button properties like name,size can be passed using own controller.From a pure design standpoint, the controller probably should not be sourcing values like name and size. Name should probably come from a resource bundle, and size should be defined by the view. The controller is primarily meant to manage the interaction between the model and the view, and respond to user input events fired by the view.

  • Problem avec bean code in controller

    Hi;
    i made a slider in scenebuilder et i added a method in the code: #ondrag.scenebuilder gives a warning:No event handler found in FXML controller class for the event ondrag
    How can i make an event handler in controller for this slider?
    regards
    Kapac

    daniel wrote:
    #ondrag.scenebuilder is not a valid method name.
    You should use #xxxxxxx where xxxxxxx is the name of a method in your controller's class.
    What you can do is:
    1. In SceneBuilder, select the node on which you want to set the handler.
    2. Open the Code section of the inspector
    3. Type in the name of the method you want to invoke when the event is fired (don't forget the leading #)
    4. Invoke View > Show Sample Skeleton Code
    5. In the window that pops up, copy the method declaration, and paste it into your controller class.
    See my post on connection to code:
    https://blogs.oracle.com/jmxetc/entry/connecting_scenebuilder_edited_fxml_to
    -- danielDaniel;thank you for your precious and quick answer ;i have always problems with slider;
    i don't understand your remark :
    #ondrag.scenebuilder is not a valid method name.
    You should use #xxxxxxx where xxxxxxx is the name of a method in your controller's class.
    because i write any name of method in builder #xxxxxxx and i copy it in controller without problem .Is a particular name to write in builder?
    my problem is :moving the cursor of the slider by a method of the builder code,i tried differents methods in drag and drop : ondragdetected;ondragdone;ondragentered;ondragexited,onmousedrag exited,onmousedragrelease,
    and in mouse
    and copyit in controller
    but if i put a breakpoint at the method the debugger is ignoring the method and the breakpoint
    i would like to make a music reader and i succeed to make a slider like a progressbar;but i can't move the cursor of the slider with the mouse in order to play another place.
    also i don't find any doc or tutorials on the different parts of the builder code? are any??

  • Setting row and column constraints in FXML

    I've set the column and row constraints in my FXML controller like this:
    RowConstraints row1 = new RowConstraints();
    row1.setVgrow(Priority.ALWAYS);
    RowConstraints row2 = new RowConstraints();
    row2.setMaxHeight(150);
    row2.setVgrow(Priority.NEVER);
    pane.getRowConstraints().addAll(row1, row2);
    ColumnConstraints column1 = new ColumnConstraints();
    column1.setMaxWidth(250);
    column1.setHgrow(Priority.NEVER);
    ColumnConstraints column2 = new ColumnConstraints();
    column2.setHgrow(Priority.ALWAYS);
    pane.getColumnConstraints().addAll(column1, column2);and it works fine but what I can't figure out is how I'll do that using only FXML?

    Hi,
    Try the following:
        <?import javafx.scene.layout.*?>
        <GridPane>
            <rowConstraints>
                <RowConstraints vgrow="ALWAYS" />
                <RowConstraints maxHeight="150" vgrow="NEVER" />
            </rowConstraints>
            <columnConstraints>
                <ColumnConstraints maxWidth="250" hgrow="NEVER"/>
                <ColumnConstraints hgrow="ALWAYS"/>
            </columnConstraints>
            <children>
            </children>
        </GridPane>Basically 'rowConstraints' and 'columnConstraints' are attributes on GridPane of type Collection.
    Hope that helps,
    zonski
    Did you find this answer useful? If so, please mark as 'correct' or 'helpful'.

  • How to load a ResourceBundle in an FXML-include

    Hi!
    Is there a way to load a resourceBundle for an included FXML-file?
    Lets me explain a bit more...
    I have a rather complex scence using a border layout. Because of the complexity, each region of the border layout includes a "Sub-"FXML. And each "Sub"-FXML has its own controller.
    My idea now is to load the resourceBundle inside the initalize method of such a "Sub"-Fxml controller, but I don't get it work. Is this even possible or do I have to load resourceBundles with the FXMLLoader, when loading my parent border layout scene?
    Any help would be much appreciated!
    J.Ishikawa
    Edited by: J. Ishikawa on May 20, 2013 12:04 AM

    Yes you can create a signed Applet to do this but what is the point? If you want to make an Applet to play media files then surely the media files to be played should reside on your server. If this is the case then there is no point in opening a file dialog to browse the client machine but rather your Applet should hold a list of files available to the user and present them with some means of choosing which one they want loaded - a JList or a JComboBox perhaps?

  • WLC 6 WLAN Override problem

    works function WLAN Override in controller WLC6?, we have tried it and it does not work, is a software problem?

    Professorguy,
    Does having to match profile name to SSID name result in not being able to have multiple authentication methods per SSID? That was supposed to be a feature of 4.0.206.
    Thanks,

  • Modularizing large FX gui apps, esp. using fxml developed by Scene Builder

    StarterApp - One large java source file.
    Trying Out the JavaFX UI Controls (Using the JavaFX UI Controls)
    StageCoach is a simpler app, but with fxml, controller, and main code in separate files.
    Allows manipulation using Scene Builder.
    https://code.google.com/p/jfxtras/source/browse/ProJavaFX/Chapter03/StageCoach?repo=samples&r=322042d9ac293fcd9dd8f63e1664df45a0c4746f
    I was lead to these by the book, Pro JavaFX 8:
    http://www.apress.com/9781430265740
    Rich as it is, the StartApp is one big piece of code, with no modules such as an fxml file.
    By spreading out the code for StarterApp and StageCoach and studying it carefully
    I should be able to build a system as large as StarterApp, but as a three-file combo.
    StarterApp has nothing that deals with concurrency or persistence - those will be my jobs.
    I'm doing this because I'm building a large NLP app.
    It needs a GUI for future users.
    - Bob F

    Take a look at some app examples from the open-jfx repository
      https://wiki.openjdk.java.net/display/OpenJFX/Quick+Start
    For a smallish app, see the ConferenceScheduleApp:
       openjfx/8u-dev/rt: 3d138300d935 /apps/experiments/ConferenceScheduleApp/
    For a (much) larger app, see SceneBuilder:
       http://hg.openjdk.java.net/openjfx/8u-dev/rt/file/3d138300d935/apps/scenebuilder
       Ladstatt: Home made JavaFX SceneBuilder
    For a minimal framework which features FXML and dependency injection, see afterburner.fx:
       http://afterburner.adam-bien.com
    You can skip all of the stuff below if you don't like reading and just want to go code...
    In general for app code, use aggregation over inheritance in most places, though inheritance is useful sometimes.  Don't try to create your own controls by extending the Control class unless you are writing control libraries - that is complex and not well documented as well as largely unnecessary for app code.  Similarly PopupWindow isn't all that great or at least I have never found a need for it in app code - a basic Stage works fine for pretty much every case except perhaps very specialized things like context menus.  Java 8 has built-in dialogs and alerts in 8u40, so for standard dialogs or some reasonably customized dialogs, using those is better than creating your own.  If the standard controls aren't enough, try ControlsFX, it is (mainly) great and high quality.
    Let resizable layout managers do the layout work for you and use constraints in the layout managers and nodes rather than mucking around with fixed sized layouts or layout through binding.
    Don't try to implement a spreadsheet in a JavaFX TableView - just use the built-in controls for what they are good at and either develop a new control for specific functionality not provided by the built-in controls or just skip that feature if it would be too expensive to build it from scratch yourself (and it probably will be expensive - you just have to justify that against your project budget whether that is money or your own time).
    Make use of WebView to bring in web components (e.g. Google Docs or Google Maps).  Don't try and pass a lot of data back and forth between a WebView and your app.
    Don't do any style in code nor in FXML, put it all in a CSS style sheet.
    For medium sized apps - use FXML to design and mark-up your GUI, and use SceneBuilder to create and edit the FXML, don't hand code basic form style UIs - in the long run the FXML based app will be easier to maintain.
    For really small apps and learning tasks, write everything in code against the API so you understand that - use no FXML at all.
    With JavaFX you are writing user interfaces, follow basic user interface design heuristics for which there are some principles to keep in mind.
    Once you have a few FXML pages, passing parameters or sharing data between them is a question that most people run into as well as how to deal with navigation.  That navigation framework I linked is super basic and just meant for pretty simple applications.  A nicer framework which worked in general like a Browser navigation model would be useful - but I haven't seen a generic implementation of such a thing yet - I guess you could create one, but I definitely wouldn't start out trying to do that - instead focus on the basics of your application and get that implemented first.  If you end up needing a reasonably sophisticated navigation framework, eventually you will know it and can evaluate what to do then.
    You can do an awful lot with CSS and styling the built-in controls.  It really is very flexible.  Learn CSS and the JavaFX variant by reading general CSS tutorials (then forget everything HTML specific) and study in depth the JavaFX CSS reference guide and understand its extensions like looked up colors and derivation functions.  When you want to know how some inbuilt thing is styled, go to the modena.css source (which can be hideously obtuse and complicated).  Use ScenicView and SceneBuilder CSS analyzer to understand how CSS is applied to elements.  Don't style borders with boxes - use layered backgrounds, that is how every control modena.css works and how your app should also work.
    Deployment is a difficult topic - so sad and depressing.  For development, just build and run in your IDE.  For production, package the app as a self-contained application. Maybe one day there will be a better deployment model for JavaFX - but that is the best you can get for now.  Completely ignore webstart and web deployment models - any time spent investigating such technologies is completely wasted.
    Do not try to integrate JavaFX and Swing or SWT.  Just write pure JavaFX apps.
    For larger apps you intend to deploy to production, use Maven or Gradle as your build system (you can google the JavaFX plugins for each).  Do not spend any time with the stand-alone JavaFX packager or the JavaFX ant tasks and do not rely on your IDE to do your production builds.
    Get help to targeted questions on StackOverflow.
    Only code to Java 8+ and make use of functional programming techniques.
    Don't write multi-threaded apps unless you know what you are doing.  When you do write multi-threaded apps, use the JavaFX concurrency utilities.  Never modify the active scene graph from another thread, nor touch a property which might trigger an event which might modify the scene graph.  Do use the concurrency utilities if you have network I/O otherwise you will freeze your app while the network I/O occurs and that is a "bad thing".
    The Oracle JavaFX 8 documentation is good - read it and run a lot of the examples (except the ant based deployment ones and the Swing/SWT integration ones).
    Ensemble is great, play with it and study the code to see for the samples (which you can view within Ensemble).
    Binding is programming by side-effect, so be aware that when you change a property, it may trigger some potentially unrelated action through bindings or attached listeners.
    Programming JavaFX in any language other than Java is an experimental thing, so only do that if you like experimenting and are prepared to do so without a lot of support.
    Targeting embedded devices, iOS or Android for a JavaFX app is an experimental thing, so only do that if, yada, yada, yada.
    JavaFX is a mid-level UI system, not a full application stack - it abstracts away the basics like rendering, controls and animation but does not provide comprehensive OS hooks, navigation frameworks, model/view/presenter frameworks, full dependency injection, client/server messaging, data <-> controls serialization and deserialization, etc.  FXML is just a markup system with a binding capability to Java code.  JavaFX and FXML do not constitute a full application framework.  There is no widely-used full application framework for JavaFX.  Sure some people have tried to create one, but none of those solutions have achieved critical mass of usage and features - plus a one-size fits all application framework will never exist anyway - client applications (e.g. a game versus a line-of-business app) differ greatly and deserve completely different architectures.
    There are many things in the Java EE world which can be used in JavaFX (e.g., its dependency injection, its web socket or rest APIs and implementations, its server based systems to allow your app to access cloud based logic and storage, etc) - so feel free to use the bits you need, usually it's as simple as adding additional library dependencies to your maven or gradle project.  A typical medium sized JavaFX application will include multiple third party libraries (mostly non-UI libraries) to get its job done as this will be more convenient than coding everything against the JRE API - though there is an awful lot of out the box functionality you get from the JRE.
    JavaFX is more complicated to use than Delphi and in some respects doesn't supply as much functionality in terms of built-in stuff like data base backed tables (though it supplies a ton more functionality in style).  It is not easier to create a complete business app using JavaFX than it would be to create a similar thing in Microsoft Access in the 90's.  Such is progress.
    JavaFX is portable across desktop environments (OS X, Windows, Mac).  JavaFX apps have their own look and feel which is not like the native OS, but that is probably fine for a lot of apps.  AquaFX does an amazing job of making a JavaFX app looks like OS X apps (kudos to the creators of both AquaFX and the JavaFX built-in styling capabilities).
    Unlike some other portable frameworks like QT, you don't have to write C code, you can write Java code (which to me at least is a win).  Similarly unlike HTML/CSS/JavaScript you don't have to write untyped JavaScript or make use of some obscure code snippet you pulled off the web for your button control.  You don't have to use the web framework of the day which withered yesterday.  Instead you have the (benefit?) of hardly any framework at all for JavaFX.  You don't have to have your app live within a browser sandbox that another developer once described as the ghetto of application sandboxes.
    So, as compared to HTML - I think JavaFX is kinder to the developer, though end users don't really seem to care that much and are fairly accepting of HTML applications even when their functionality is often inferior to many more traditional GUI apps.  HTML is standardized, its full of standards, even the non-standard parts.  Everybody used to implement all the standards differently or make their own standards, however now the standards are so painstakingly, nitpickingly prescriptive that everybody implements pretty much the same thing - except when they don't.  JavaFX has no standard but its public API docs, it has just one implementation.  If you code against the API, your app is probably going to work forever - at least if you bundle the runtime with your app, cause if you don't you might end up like the poor guy in the previous question who can't figure out how to update his app specific CSS rules to get his app to look the same with a newer Java version.  JavaFX is a relatively niche technology and you don't have the legion of developers, tinkerers, industry investments and people just plain getting stuff done in any which way that you have with the whole HTML juggernaut.  The major thing that HTML provides that JavaFX does not is: Sharable, browsable deep links to stuff with search indexed content.  With HTML, Google will index it and you can link to and refer to other docs and other docs can link to yours.  It is the HT in HTML which makes the web so amazing and the F in FXML doesn't match it.  What is the F anyway?
    That's a huge wall'o'text.  Just some random thoughts and opinions.  All opinions are my own.  Your opinions may vary.  That's OK.  I don't think a discussion is needed.  If you would like any clarification or further advice you can ask in new questions.

  • I am getting a NullPointerException when trying to use the Service class

    I am getting a NullPointerException which is as follows
    java.lang.NullPointerException
    file:/K:/Learner/JavaFx2/ProductApplication/dist/run166129449/ProductApplication.jar!/com/product/app/view/viewsingle.fxml
      at com.product.app.controller.ViewSingleController.initialize(ViewSingleController.java:70)
      at javafx.fxml.FXMLLoader.load(Unknown Source)
      at javafx.fxml.FXMLLoader.load(Unknown Source)
    And my View SingleController is as follows
    package com.product.app.controller;
    import com.product.app.model.Product;
    import com.product.app.service.ViewProductsService;
    import com.product.app.util.JSONParser;
    import com.product.app.util.TagConstants;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.ResourceBundle;
    import javafx.collections.ObservableList;
    import javafx.concurrent.Service;
    import javafx.concurrent.Task;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.ProgressIndicator;
    import javafx.scene.control.TextArea;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.Region;
    import javafx.stage.Stage;
    import javax.swing.JOptionPane;
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONObject;
    * FXML Controller class
    * @author Arun Joseph
    public class ViewSingleController implements Initializable {
        private static String action = "";
        @FXML
        private TextField txtID;
        @FXML
        private TextField txtName;
        @FXML
        private TextField txtPrice;
        @FXML
        private TextArea txtDesc;
        @FXML
        private Region veil;
        @FXML
        private ProgressIndicator p;
        private ViewProductsService service = new ViewProductsService();
        private JSONObject product = null;
        private JSONParser parser = new JSONParser();
        private int pid = 1;
        public void setPid(int pid) {
            this.pid = pid;
         * Initializes the controller class.
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            veil.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4)");
            p.setMaxSize(150, 150);
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
            Product product = new Product();
            service.start();
            ObservableList<Product> products = service.valueProperty().get();
            products.get(pid);
            txtID.textProperty().set(String.valueOf(products.get(pid).getPid()));
            //product = service.valueProperty().get().get(pid);
            //txtID.setText(String.valueOf(product.getPid()));
            txtName.textProperty().set(product.getName());
            txtPrice.textProperty().set(String.valueOf(product.getPrize()));
            txtDesc.textProperty().set(product.getDescription());
        private SomeService someService = new SomeService();
        @FXML
        private void handleUpdateButtonClick(ActionEvent event) {
            action = "update";
            someService.start();
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
        @FXML
        private void handleDeleteButtonClick(ActionEvent event) {
            action = "delete";
            someService.start();
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
        @FXML
        private void handleCancelButtonClick(ActionEvent event) {
            closeStage();
        private void closeStage() {
            ViewSingleController.stage.close();
        private static Stage stage = null;
        public static void setStage(Stage stage) {
            ViewSingleController.stage = stage;
        private class SomeService extends Service<String> {
            @Override
            protected Task<String> createTask() {
                return new SomeTask();
            private class SomeTask extends Task<String> {
                @Override
                protected String call() throws Exception {
                    String result = "";
                    int success = 0;
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    switch (action) {
                        case "update":
                            params.add(new BasicNameValuePair("pid", txtID.getText()));
                            params.add(new BasicNameValuePair("name", txtName.getText()));
                            params.add(new BasicNameValuePair("price", txtPrice.getText()));
                            params.add(new BasicNameValuePair("description", txtDesc.getText()));
                            product = parser.makeHttpRequest(TagConstants.url_update_product_with_id, "POST", params);
                            success = product.getInt(TagConstants.TAG_SUCCESS);
                            if (success == 1) {
                                result = "Successfully Updated the product";
                                JOptionPane.showMessageDialog(null, result);
                                closeStage();
                            break;
                        case "delete":
                            params.add(new BasicNameValuePair("pid", txtID.getText()));
                            product = parser.makeHttpRequest(TagConstants.url_delete_product_with_id, "POST", params);
                            success = product.getInt(TagConstants.TAG_SUCCESS);
                            if (success == 1) {
                                result = "Successfully Deleted the product";
                                JOptionPane.showMessageDialog(null, result);
                                closeStage();
                            break;
                    return result;

    Time Machine has its own mechanism for deleting files. The number you are seeing may represent a "underflow" or a number of files which exceeds the limit and becomes negative.
    The best way to remove TM files is via the TM interface: select the files and click the Gear and select delete from all backups.
    If you are deleting files on an external drive which once included TM files, it is best to use the terminal and just delete them directly. They go bye-bye without ever seeing the trash bucket.
    Of course, using the terminal is not for everyone.
    What you might be able to do is restore the files from trash and then delete them properly or in smaller bundles.

  • 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 ;
    }

  • Problem in scene builder

    Hi;
    when i put a new control on the scene i get the warning:
    No injectable field found in FXML Controller class for the id chb
    what is the meaning of this warning and what is FXML controller and where to find it
    regards

    Hi,
    For each FXML file, you can define a controller class, which will be instantiated by the FXML loader - and which is how you can connect the objects defined in FXML to your own application logic.
    See here for a brief description on how this works: Re: Loading and Unloading of FXML components at runtime
    What makes the connection between the variable in the controller class and the object in the FXML file is the value of the object's fx:id.
    When you set an fx:id on an object - the SceneBuilder tries to parse the controller class in order to see whether the class has a variable of that name. If it doesn't find any - it displays a warning - which is a reminder for you that you may want to add such a variable to the controller class.
    Usually however, these wranings only appear if you have defined a controller class, and if SceneBuilder has found it.
    The controller class can be set by selecting the root node in the HierarchyPanel, then opening the Code section in the inspector. You should see a textfield at the top in which you can set the full name of the class.
    Hope this helps,
    -- daniel

  • Arrow in menubar

    Hi guys,
    I've a small problem. I've a BorderPain and in the top I've a MenuBar with some MenuItem (1 ord two for every Menu). When I click in the menu the menu is opened but is displayed a down arrow and only one menuitem is displayed!!!
    It's very strage, infact after I clicked on the arrow the menu is show entirely and no arrow is displayed.
    Any suggestion?
    Thanks very much

    Sorry but that is the only code that create the menu. It's very strange infact in my scenebuilder in preview mode I've not this problem but after, when I run the application I have the arrow in the menu.
    This is the controller of the main app where there is the menu:
    public class OdontoxController implements Initializable {
        private Main application;
        @FXML //  fx:id="container"
        private Pane container; // Value injected by FXMLLoader
    //    @FXML //  fx:id="itemLavorazioni"
    //    private MenuItem itemLavorazioni; // Value injected by FXMLLoader
    //    @FXML //  fx:id="itemClienti"
    //    private MenuItem itemClienti; // Value injected by FXMLLoader
    //    @FXML //  fx:id="itemMovimenti"
    //    private MenuItem itemMovimenti; // Value injected by FXMLLoader
    //    @FXML //  fx:id="itemProdotti"
    //    private MenuItem itemProdotti; // Value injected by FXMLLoader
    //    @FXML //  fx:id="menuAnagrafiche"
    //    private Menu menuAnagrafiche; // Value injected by FXMLLoader
    //    @FXML //  fx:id="menuLavorazioni"
    //    private Menu menuLavorazioni; // Value injected by FXMLLoader
    //    @FXML //  fx:id="menubar"
    //    private MenuBar menubar; // Value injected by FXMLLoader
    //    @FXML //  fx:id="menucontabilita"
    //    private Menu menucontabilita; // Value injected by FXMLLoader
        @FXML //  fx:id="vbox"
        private VBox vbox; // Value injected by FXMLLoader
        @FXML //  fx:id="headerApp"
        private Pane headerApp; // Value injected by FXMLLoader
        @Override // This method is called by the FXMLLoader when initialization is complete
        public void initialize(URL fxmlFileLocation, ResourceBundle resources) {
    //        assert itemClienti != null : "fx:id=\"itemClienti\" was not injected: check your FXML file 'Odontox.fxml'.";
    //        assert itemLavorazioni != null : "fx:id=\"itemLavorazioni\" was not injected: check your FXML file 'Odontox.fxml'.";
    //        assert itemMovimenti != null : "fx:id=\"itemMovimenti\" was not injected: check your FXML file 'Odontox.fxml'.";
    //        assert itemProdotti != null : "fx:id=\"itemProdotti\" was not injected: check your FXML file 'Odontox.fxml'.";
    //        assert menuAnagrafiche != null : "fx:id=\"menuAnagrafiche\" was not injected: check your FXML file 'Odontox.fxml'.";
    //        assert menuLavorazioni != null : "fx:id=\"menuLavorazioni\" was not injected: check your FXML file 'Odontox.fxml'.";
    //        assert menubar != null : "fx:id=\"menubar\" was not injected: check your FXML file 'Odontox.fxml'.";
    //        assert menucontabilita != null : "fx:id=\"menucontabilita\" was not injected: check your FXML file 'Odontox.fxml'.";
            assert vbox != null : "fx:id=\"vbox\" was not injected: check your FXML file 'Odontox.fxml'.";
            // initialize your logic here: all @FXML variables will have been injected
            start();
        private void start() {
        public void setApp(Main application) {
            this.application = application;
        // Handler for Menu[fx:id="menuLavorazioni"] onAction
        public void processLavorazioni(ActionEvent event) {
            try {
                LavoriController controller = (LavoriController) replaceSceneContent("lavori/Lavori.fxml");
                controller.setOdontoxController(this);
            } catch (Exception ex) {
                ex.printStackTrace();
        public void processNuovaLavorazione(ActionEvent event) {
            try {
                LavoriDettaglioController controller = (LavoriDettaglioController) replaceSceneContent("lavori/LavoriDettaglio.fxml");
                controller.setOdontoxController(this);
            } catch (Exception ex) {
                ex.printStackTrace();
        // Handler for Menu[fx:id="menuLavorazioni"] onAction
        public void processClienti(ActionEvent event) {
            try {
                ClientiController controller = (ClientiController) replaceSceneContent("clienti/Clienti.fxml");
                controller.setApp(application);
            } catch (Exception ex) {
                ex.printStackTrace();
        // Handler for MenuItem[fx:id="itemMovimenti"] onAction
        public void processMovimenti(ActionEvent event) {
            try {
                MovimentiController controller = (MovimentiController) replaceSceneContent("movimenti/Movimenti.fxml");
                controller.setApp(application);
            } catch (Exception ex) {
                ex.printStackTrace();
        // Handler for MenuItem[fx:id="itemProdotti"] onAction
        public void processProdotti(ActionEvent event) {
            try {
                ProdottiController controller = (ProdottiController) replaceSceneContent("prodotti/Prodotti.fxml");
                controller.setApp(application);
            } catch (Exception ex) {
                ex.printStackTrace();
        public Initializable replaceSceneContent(String fxml) throws Exception {
            FXMLLoader loader = new FXMLLoader();
            InputStream in = OdontoxController.class.getResourceAsStream(fxml);
            loader.setBuilderFactory(new JavaFXBuilderFactory());
            loader.setLocation(OdontoxController.class.getResource(fxml));
            AnchorPane page;
            try {
                page = (AnchorPane) loader.load(in);
            } finally {
                if (in != null) {
                    in.close();
            container.getChildren().clear();
            container.getChildren().add(page);
            return (Initializable) loader.getController();
    }As you can see I have commented the code that refers the menu as test but not even in this case the menu works fine.
    Any ideas?
    Thanks

  • Help needed for Service class

    When trying to retrieve information for a form that contains textbox so as to display product information on a form I am getting an error which is listed below
    java.lang.NullPointerException
    file:/K:/Learner/JavaFx2/ProductApplication/dist/run876373360/ProductApplication.jar!/com/product/app/view/viewsingle.fxml
      at com.product.app.controller.ViewSingleController.initialize(ViewSingleController.java:70)
    and here is the code for controller as well as service class
    package com.product.app.controller;
    import com.product.app.model.Product;
    import com.product.app.service.ViewProductsService;
    import com.product.app.util.JSONParser;
    import com.product.app.util.TagConstants;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.ResourceBundle;
    import javafx.collections.ObservableList;
    import javafx.concurrent.Service;
    import javafx.concurrent.Task;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.control.ProgressIndicator;
    import javafx.scene.control.TextArea;
    import javafx.scene.control.TextField;
    import javafx.scene.layout.Region;
    import javafx.stage.Stage;
    import javax.swing.JOptionPane;
    import org.apache.http.NameValuePair;
    import org.apache.http.message.BasicNameValuePair;
    import org.json.JSONArray;
    import org.json.JSONObject;
    * FXML Controller class
    * @author Arun Joseph
    public class ViewSingleController implements Initializable {
        private static String action = "";
        @FXML
        private TextField txtID;
        @FXML
        private TextField txtName;
        @FXML
        private TextField txtPrice;
        @FXML
        private TextArea txtDesc;
        @FXML
        private Region veil;
        @FXML
        private ProgressIndicator p;
        private ViewProductsService service = new ViewProductsService();
        private JSONObject product = null;
        private JSONParser parser = new JSONParser();
        private int pid = 1;
        public void setPid(int pid) {
            this.pid = pid;
         * Initializes the controller class.
        @Override
        public void initialize(URL url, ResourceBundle rb) {
            veil.setStyle("-fx-background-color: rgba(0, 0, 0, 0.4)");
            p.setMaxSize(150, 150);
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
            Product product = new Product();
            service.start();
            ObservableList<Product> products = service.valueProperty().get();
            products.get(pid);
            txtID.textProperty().set(String.valueOf(products.get(pid).getPid()));
            //product = service.valueProperty().get().get(pid);
            //txtID.setText(String.valueOf(product.getPid()));
            txtName.textProperty().set(product.getName());
            txtPrice.textProperty().set(String.valueOf(product.getPrize()));
            txtDesc.textProperty().set(product.getDescription());
        private SomeService someService = new SomeService();
        @FXML
        private void handleUpdateButtonClick(ActionEvent event) {
            action = "update";
            someService.start();
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
        @FXML
        private void handleDeleteButtonClick(ActionEvent event) {
            action = "delete";
            someService.start();
            p.progressProperty().bind(service.progressProperty());
            veil.visibleProperty().bind(service.runningProperty());
            p.visibleProperty().bind(service.runningProperty());
        @FXML
        private void handleCancelButtonClick(ActionEvent event) {
            closeStage();
        private void closeStage() {
            ViewSingleController.stage.close();
        private static Stage stage = null;
        public static void setStage(Stage stage) {
            ViewSingleController.stage = stage;
        private class SomeService extends Service<String> {
            @Override
            protected Task<String> createTask() {
                return new SomeTask();
            private class SomeTask extends Task<String> {
                @Override
                protected String call() throws Exception {
                    String result = "";
                    int success = 0;
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    switch (action) {
                        case "update":
                            params.add(new BasicNameValuePair("pid", txtID.getText()));
                            params.add(new BasicNameValuePair("name", txtName.getText()));
                            params.add(new BasicNameValuePair("price", txtPrice.getText()));
                            params.add(new BasicNameValuePair("description", txtDesc.getText()));
                            product = parser.makeHttpRequest(TagConstants.url_update_product_with_id, "POST", params);
                            success = product.getInt(TagConstants.TAG_SUCCESS);
                            if (success == 1) {
                                result = "Successfully Updated the product";
                                JOptionPane.showMessageDialog(null, result);
                                closeStage();
                            break;
                        case "delete":
                            params.add(new BasicNameValuePair("pid", txtID.getText()));
                            product = parser.makeHttpRequest(TagConstants.url_delete_product_with_id, "POST", params);
                            success = product.getInt(TagConstants.TAG_SUCCESS);
                            if (success == 1) {
                                result = "Successfully Deleted the product";
                                JOptionPane.showMessageDialog(null, result);
                                closeStage();
                            break;
                    return result;

    Is line 70 in the code above
    txtPrice.textProperty().set(String.valueOf(product.getPrize()));
    also line 70 in your original code? (Sometimes the syntax highlighter seems to delete blank lines.) If so, then txtPrice must be null, which would likely be caused by the fx:id attribute for it being set incorrectly in the fxml file.
    Check which is line 70 in the original code though.

  • Scene Builder questions

    Hello all!
    I am curious about a few things with Scene builder 1.0 and 1.1.
    1. How come there is 3D rotations and such, but there are only 2D shapes? No cubes or anything....
    2. Why is there touch, and swipe settings if JavaFX isn't on mobile right now(Which is what I read, but I heard that at the last JavaOne there was Android with JavaFX)??
    3. Why isnt there more versatility within the inners of charts and such. We have to do all of that manually, which I can understand, but it would be nice to set up everything via scene builder...
    I have seen you can make custom controls, what about shapes? I still need to read more of the docs. I think it's ridiculous there aren't 3D shapes, I really need cubes for a project.... Pictures on each side would be nice too :)

    I also am having another issue now.... I am able to make my dice rotate and have images perfectly if I make a normal FX class, but when I use the FXML, Controller Class, and Main class I get some funky cubes.....
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import java.net.URL;
    import java.util.ResourceBundle;
    import javafx.animation.Animation;
    import javafx.animation.KeyFrame;
    import javafx.animation.KeyValue;
    import javafx.animation.Timeline;
    import javafx.application.Application;
    import javafx.event.ActionEvent;
    import javafx.fxml.FXML;
    import javafx.fxml.Initializable;
    import javafx.scene.Group;
    import javafx.scene.Node;
    import javafx.scene.control.Label;
    import javafx.scene.image.Image;
    import javafx.scene.layout.Pane;
    import javafx.scene.paint.ImagePattern;
    import javafx.scene.shape.RectangleBuilder;
    import javafx.scene.transform.Rotate;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    * @author Konrad
    public class ZonkController
        Image d1 = new Image(getClass().getResourceAsStream("Dice1.gif"));
        Image d2 = new Image(getClass().getResourceAsStream("Dice2.gif"));
        Image d3 = new Image(getClass().getResourceAsStream("Dice3.gif"));
        Image d4 = new Image(getClass().getResourceAsStream("Dice4.gif"));
        Image d5 = new Image(getClass().getResourceAsStream("Dice5.gif"));
        Image d6 = new Image(getClass().getResourceAsStream("Dice6.gif"));
        private Timeline animation;
        @FXML
        private Pane pane;
        @FXML
        private Label label;
        @FXML
        private void handleButtonAction(ActionEvent event) {
            System.out.println("You clicked me!");
            label.setText("Hello World!");
            pane.getChildren().add(content());
            animation.play();
        public Node content()
            Cube c = new Cube(105);
            c.rx.setAngle(45);
           c.ry.setAngle(45);
            Cube c2 = new Cube(100);
            c2.setTranslateX(200);
            c2.rx.setAngle(45);
            c2.ry.setAngle(45);
            Cube c3 = new Cube(105);
            c3.setTranslateX(-200);
            c3.rx.setAngle(45);
            c3.ry.setAngle(45);
             Cube c4 = new Cube(105);
            c4.setTranslateX(-400);
                    Cube c5 = new Cube(105);
            c5.setTranslateX(400);
            animation = new Timeline();
            animation.getKeyFrames().addAll(
                   new KeyFrame(Duration.ZERO,
                            new KeyValue(c.ry.angleProperty(), 0d),
                            new KeyValue(c2.rx.angleProperty(), 0d),
                            new KeyValue(c3.rx.angleProperty(), 0d),
                            new KeyValue(c4.ry.angleProperty(), 0d),
                            new KeyValue(c5.rx.angleProperty(), 0d)
                    new KeyFrame(Duration.seconds(1),
                            new KeyValue(c.ry.angleProperty(), 360d),
                            new KeyValue(c2.rx.angleProperty(), 360d),
                            new KeyValue(c3.rz.angleProperty(), 360d),
                            new KeyValue(c4.rx.angleProperty(), 360d),
                            new KeyValue(c5.ry.angleProperty(), 360d)
            animation.setCycleCount(Animation.INDEFINITE);
            return new Group(c,c2,c3,c4,c5);
        public class Cube extends Group
            final Rotate rx = new Rotate(0,Rotate.X_AXIS);
            final Rotate ry = new Rotate(0,Rotate.Y_AXIS);
            final Rotate rz = new Rotate(10,20,30);
            public Cube(double size) {
                getTransforms().addAll(rz, ry, rx);
                getChildren().addAll(
                    RectangleBuilder.create() // back face
                        .width(size).height(size)
                        .fill(new ImagePattern(d1))
                        .translateX(-0.5*size)
                        .translateY(-0.5*size)
                        .translateZ(0.5*size)
                        .build(),
                    RectangleBuilder.create() // bottom face
                        .width(size).height(size)
                        .fill(new ImagePattern(d2))
                        .translateX(-0.5*size)
                        .translateY(0)
                        .rotationAxis(Rotate.X_AXIS)
                        .rotate(90)
                        .build(),
                    RectangleBuilder.create() // right face
                        .width(size).height(size)
                        .fill(new ImagePattern(d3))
                        .translateX(-1*size)
                        .translateY(-0.5*size)
                        .rotationAxis(Rotate.Y_AXIS)
                        .rotate(90)
                        .build(),
                    RectangleBuilder.create() // left face
                        .width(size).height(size)
                        .fill(new ImagePattern(d4))
                        .translateX(0)
                        .translateY(-0.5*size)
                        .rotationAxis(Rotate.Y_AXIS)
                        .rotate(90)
                        .build(),
                    RectangleBuilder.create() // top face
                        .width(size).height(size)
                        .fill(new ImagePattern(d5))
                        .translateX(-0.5*size)
                        .translateY(-1*size)
                        .rotationAxis(Rotate.X_AXIS)
                        .rotate(90)
                        .build(),
                    RectangleBuilder.create() // top face
                        .width(size).height(size)
                        .fill(new ImagePattern(d6))
                        .translateX(-0.5*size)
                        .translateY(-0.5*size)
                        .translateZ(-0.5*size)
                        .build()
    }Main
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    import javafx.application.Application;
    import javafx.fxml.FXMLLoader;
    import javafx.scene.DepthTest;
    import javafx.scene.Parent;
    import javafx.scene.Scene;
    import javafx.scene.transform.Translate;
    import javafx.stage.Stage;
    * @author Konrad
    public class Zonk extends Application {
        @Override
        public void start(Stage stage) throws Exception {
            Parent root = FXMLLoader.load(getClass().getResource("Zonk.fxml"));
            ZonkController z = new ZonkController();
            Scene scene = new Scene(root, 2000,2000,true);
            stage.setScene(scene);
            stage.show();
            root.setDepthTest(DepthTest.ENABLE);
            root.getTransforms().addAll(new Translate(2000 / 2, 750 / 2));
         * The main() method is ignored in correctly deployed JavaFX application.
         * main() serves only as fallback in case the application can not be
         * launched through deployment artifacts, e.g., in IDEs with limited FX
         * support. NetBeans ignores main().
         * @param args the command line arguments
        public static void main(String[] args) {
            launch(args);
    }<?xml version="1.0" encoding="UTF-8"?>
    <?import java.lang.*?>
    <?import java.util.*?>
    <?import javafx.scene.*?>
    <?import javafx.scene.control.*?>
    <?import javafx.scene.layout.*?>
    <AnchorPane id="AnchorPane" prefHeight="363.0" prefWidth="320.0" xmlns:fx="http://javafx.com/fxml" fx:controller="ZonkController">
      <children>
        <Button fx:id="button" layoutX="126.0" layoutY="90.0" onAction="#handleButtonAction" text="Click Me!" />
        <Label fx:id="label" layoutX="126.0" layoutY="120.0" minHeight="16.0" minWidth="69.0" />
        <Pane fx:id="pane" layoutX="60.0" layoutY="136.0" prefHeight="200.0" prefWidth="200.0" />
      </children>
    </AnchorPane>

  • NSTabView - selector not recognized using selectLastTabViewItem and friends

    Hi, I'm new to Xcode, Cocoa, and Objective-C (not new to development though). I am using Xcode 2.4.1 on OS X 10.4.11.
    I've gotten on pretty well doing general stuff with most of the widgets, but I'm hung up trying to do something (commonplace) with tabs. I have a NSTabView with 3 tabs, and want to force one of them to become the active tab.
    After a couple hours of screwing with this, I have created a new Xcode project just to test selectLastTabViewItem on a NSTabView. This is exactly what I do:
    1) In Xcode, create new Cocoa application project.
    2) Add class Controller there
    3) Open the MainMenu.nib
    4) In IB, drop the Controller.h file so it appears with the classes.
    5) Instantiate a Controller class
    6) Drop a NSTabView in the Window
    7) Create an outlet of NSTabView type for Controller
    8) Click and drag from Controller instantiated object to the NSTabView object in the GUI - connect it as an outlet. I've verified this has added properly, and in the list of outlets it picks up the "type" of NSTabView i.e. Under Controller's Connects, I see NSTabView (Tab, View)
    9) Create code for Controller, Overwrite code in Xcode with this. (No more work done in IB)
    10) Back in Xcode, edit the source and make Controller.m read as follows:
    #import "Controller.h"
    @implementation Controller
    // Simplest case is to have this code run when awakeFromNib happens
    // I've also tried it tied to a button click action
    - (void)awakeFromNib
    [tabView selectLastTabViewItem]; // select the Tab View Item called 'View'...
    // I've used the other similar methods, such as the one that selects tab view based on
    // identifier. I get the same error with all of them, this one seems easiest to debug
    // since there's the least involved
    @end
    What I get is:
    [Session started at 2009-08-02 16:00:12 -0400.]
    2009-08-02 16:00:12.955 NSTabViewTest[10808] * -[NSTabView selectLastTabViewItem]: selector not recognized [self = 0x3515f0]
    2009-08-02 16:00:12.956 NSTabViewTest[10808] An uncaught exception was raised
    2009-08-02 16:00:12.956 NSTabViewTest[10808] * -[NSTabView selectLastTabViewItem]: selector not recognized [self = 0x3515f0]
    2009-08-02 16:00:12.956 NSTabViewTest[10808] * Uncaught exception: <NSInvalidArgumentException> * -[NSTabView selectLastTabViewItem]: selector not recognized [self = 0x3515f0]
    I've looked up code online and I don't seem to be doing anything different than examples, although I don't know what their nib's look like.. any help would be wonderful. Thanks!
    Message was edited by: Robert Is Confused, fixing to use code tags

    Hi Robert, and welcome to the Dev Forums!
    selectLastTabViewItem: takes one arg which passes the sender's address to the tabView.
    - (void)awakeFromNib { // this line starts with a -, but apple forum prevents it
    NSLog(@"Controller awakeFromNib");
    [tabView selectLastTabViewItem:self]; // select the Tab View Item called 'View'...
    I think your compiler should have given you a warning: 'NSTabView' may not respond to '-selectLastTabViewItem'. These are easy to miss if you don't have your Build Results window open, since the warning bubble may not show up in the source editor until that window is reselected.
    Btw, there's a yellow alert notice in the 1st slot of the forum topics page with code formatting instructions in the subject line (and a link to lots of other handy formatting tricks). You can see how your post will look by clicking the Preview tab on top of the Reply editor panel. If you reply to my post, click the double-quote icon under Preview to see exactly how my message was formatted.
    - Ray

Maybe you are looking for