Marge and Javafx

Hi, sorry for my english.
I have this code
import java.lang.*;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import net.java.dev.marge.inquiry.DeviceDiscoverer;
import net.java.dev.marge.inquiry.InquiryListener;
    class Model {
        var inquiryListener: InquiryListener;
        var foundDevices : RemoteDevice[];
        var inquiryBtnEnabled : Boolean;
        var cancelBtnEnabled : Boolean;
    var model = Model {
        var self: Self
        inquiryBtnEnabled : true
        cancelBtnEnabled : false
        var inquiryListener = new InquiryListener()
     inquiryListener : {
                     function deviceDiscovered(device :RemoteDevice  , deviceClass:DeviceClass ) {
                        insert device as last into self.foundDevices;
                    function inquiryCompleted(devices: RemoteDevice[]) {
                        self.inquiryBtnEnabled = true;
                        self.cancelBtnEnabled = false;
                    function inquiryError() {
                        self.foundDevices = null;
                        MessageDialog {
                            title: "Error"
                            message: "Inquiry Error"
                            visible: true
                        self.inquiryBtnEnabled = true;
                        self.cancelBtnEnabled = false;
    };What is wrong?
Are there tutorial on javafx and bluetooth on-line with new syntax of JavaFx?
Thanks in advance.

Thanks for the reply.
Now i have this problem.
>
When i compile with ........
- javafxc mah.fx
This is the result:
mah.fx:22: warning: Function deviceDiscovered(javax.bluetooth.RemoteDevice,javax
.bluetooth.DeviceClass) overrides another, it should be declared 'override'.
function deviceDiscovered(device :RemoteDevice , deviceCla
ss:DeviceClass ) {
^
mah.fx:31: warning: Function inquiryError() overrides another, it should be decl
ared 'override'.
function inquiryError() {
^
mah.fx:20: InquiryListener$anon1 is not abstract and does not override abstract
method inquiryCompleted(javax.bluetooth.RemoteDevice[]) in net.java.dev.marge.in
quiry.InquiryListener
inquiryListener: InquiryListener
^
1 error
2 warnings
>
This the code
import java.lang.*;
import javax.bluetooth.RemoteDevice;
import javax.bluetooth.DeviceClass;
import javax.bluetooth.DiscoveryAgent;
import net.java.dev.marge.inquiry.DeviceDiscoverer;
import net.java.dev.marge.inquiry.InquiryListener;
    class Model {
        var inquiryListener: InquiryListener;
        var foundDevices : RemoteDevice[];
        var inquiryBtnEnabled : Boolean;
        var cancelBtnEnabled : Boolean;
    var model:Model = Model{
        inquiryBtnEnabled : true
        cancelBtnEnabled : false
        inquiryListener: InquiryListener
                     function deviceDiscovered(device :RemoteDevice  , deviceClass:DeviceClass ) {
                        insert device into model.foundDevices;
                    function inquiryCompleted(devices: RemoteDevice[]) {
                        model.inquiryBtnEnabled = true;
                        model.cancelBtnEnabled = false;
                    function inquiryError() {
                        model.foundDevices = null;
                        model.inquiryBtnEnabled = true;
                        model.cancelBtnEnabled = false;
    };What is the problem?

Similar Messages

  • Is it possible to have java and javafx project types combined ?.

    Today, in NetBeans (not sure about the eclipse world) one has to decide between a "Java" project or a "JavaFX" project.
    Why can't these two be combined ?.
    For e.g, when I try to add JavaFX files (script, classes) to a Java Project it fails to compile. I poked around Netbeans and googled a bit and could'nt find any answers.
    The only way that I can make it work is to create a JavaFX project and Java code to it.
    In situations where one is attempting to "add" JavaFX to an existing Java/Swing app the current approach is too weird and abnormal.
    For e.g Amy Fowler's excellent guide http://weblogs.java.net/blog/2009/06/10/insiders-guide-mixing-swing-and-javafx should be such that I should be able to "simply" add JavaFX code and NetBeans should take care of the plumbing. (calling javafx compiler, adding the right jars for runtime ...)
    /rk

    I'm not sure how JavaFX works, but it is built rather differently from "normal" Java (Single threaded, high level of abstraction from the actual implementation, etc). It is easy to use Java classes inside a JavaFX class, but the reverse is not true.
    Plus, though this part is technically fixable, some classes installed inside the JRE don't seem to work by default in a netbeans JavaFX project.

  • JavaServer Faces and JavaFX

    Is JavaServer Faces and JavaFX the same?

    Nope, Java FX was only announced in May 2007 whereas JSF has been around for a few years now. JSF is a framework and JavaFX are a series of products.
    Try looking up Wikipedia for the info:
    http://en.wikipedia.org/wiki/Java_FX
    http://en.wikipedia.org/wiki/Java_Server_Faces
    Illu

  • Build java and javafx applications

    Hello everybody! Currently, I am building a netbeans project that consist of java and javax applications and the questions are :
    1. How to call java object in javafx object or it reverse. Which one the better?
    2. How to compile and run the project that consist of java and javafx applications.
    Help me, please!Thank's

    Also, If you want to call JavaFX methods from Java you can use interface and have the JavaFX class extend it (interfaces are extended in JavaFX)
    For example, make interface FXAdapter.java
    interface FXAdapter {
         public void modifyLayout();
    }And in your FX class
    public class FXClass extends FXAdapter {
         public override function modifyLayout() : Void { /*Implementation*/ }
    }Now in your java class you can ask for FXAdapter as a parameter and pass a FXClass object

  • Netbeans version and JavaFx

    Hi guys
    It's a bit unclear at this stage as to what to do to get Netbeans and Javafx updated correctly.
    Do I need to still be downloading the Development version of Netbeans or have the plugin fixes been applied to Netbeans 7.01 now?
    The new development Netbeans indicates that it supports JavaFx as part of the package.. so does that mean you still need to install all of the plugins?
    It's confusing and slowing down development a lot - especially with updating javafx across multiple machines and the documentation is not covering
    how best to move from one build of Javafx to the next and how to also ensure Netbeans is setup correctly.
    -- some history since build 42 we could not package our app with netbeans. So we installed the development netbeans and had to muck around with the platform
    manager to get it to work with javafx. It has been somewhat inconsistent across several machines also - some with win7 and some XP.
    I understand that being part of a beta requires some patience but some guidance in how others are keeping their windows based development environments working properly
    would be great!

    You need to use the latest beta of NetBeans 7.1. I suspect the older version you downloaded is using JFX1.x.
    See this: http://netbeans.org/kb/docs/java/javafx-setup.html
    Regarding your threading model, there is a new API for threading but I wouldn't say it's much simpler or easier - at best, more powerful.
    There doesn't seem to be any good official docco on this however (seems like a big important topic so this is weird - maybe I just missed it). The closest is this slightly outdated article: http://fxexperience.com/2011/07/worker-threading-in-javafx-2-0/
    You may also find this useful: Thoughts on best practices for busy/wait and threads?
    If you have further questions on this stuff, probably best to start a new forum topic (or reply to the threading one above) - this thread is starting to lose relevance to it's original topic.
    Cheers,
    zonski

  • Netbeans 7 and JavaFX plugin

    Am I the only one who cannot get the JavaFX plugin to work with Netbeans 7?
    Have downloaded NB 7
    Have installed Javafx 2.0 runtime
    Have downloaded and installed javafx 2.0 nb plugins according to the installation instructions.
    Then restarting gives errors about NB plugins - which have to be disabled before continuing.
    Have tried on two PCs and had the same problem. The nb plugins seem to destroy basic functionality in Netbeans (cannot create new projects)

    Hi guys,
    can any one tell me where to find .NMB files .
    i installed Javafx run time and javafx 2.0 net beans plug in. but later i tried to add plugin in netbeans 7.0 but i couldn't find any .nmb files.
    please let me know how to overcome this issue.
    regards
    JavafxUser

  • Binding issue between POJO properties and JavaFX components

    Currently, what I want to do is use bidirectionnal binding between POJO properties and JavaFX components.
    For example, if the property is a String, a Textfield will be generated and binded with it.
    My POJOs are generated by JAXB.
    To do that, I proceeded as followed :
    In order to make the binding works I changed the default generation of JAXB
    I created a factory which takes a class instance at input and return a Map containing the POJO properties as key and the JavaFX components as value
    I displayed this map in a JFXPanel
    Here is a sample of the factory  :
    public static Map<Field, Node> createComponents(Object obj) throws NoSuchMethodException
               Map<Field, Node> map = new LinkedHashMap<Field, Node>();
               for (final Field field : obj.getClass().getDeclaredFields())
                   @SuppressWarnings("rawtypes")
                   Class fieldType = field.getType();
                   if (fieldType.equals(boolean.class) || (fieldType.equals(Boolean.class))) //Boolean
                       map.put(field, createBool(obj, field));
                   else if (fieldType.equals(int.class) || (fieldType.equals(Integer.class))) //Integer
                      map.put(field, createInt(obj, field));
                   else if (fieldType.equals(BigInteger.class)) //BigInteger
                      map.put(field, createBigInt(obj, field));
                   else if (fieldType.equals(long.class) || fieldType.equals(Long.class)) //Long
                      map.put(field, createLong(obj, field));
                   else if (fieldType.equals(String.class)) //String
                      map.put(field, createString(obj, field));
               return map;  
    public static Node createBool(Object obj, final Field field) throws NoSuchMethodException
       System.out.println(field.getType().getSimpleName() + " spotted");
       JavaBeanBooleanProperty boolProperty = JavaBeanBooleanPropertyBuilder.create().bean(obj).name(field.getName()).build();
      boolProperty.addListener(new ChangeListener<Boolean>() {
       @Override
       public void changed(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2)
      prettyPrinter(field, arg1, arg2);
       CheckBox cb = new CheckBox();
      cb.setText(" : " + field.getName());
      cb.selectedProperty().bindBidirectional(boolProperty);
       return cb;}
    So, the problem I have is : Sometimes the binding will work and sometimes it won't. For example, the binding is working unless I changed the declaration property order in the POJO, or unless I resized the panel where components are displayed.
    Does anybody have an idea of what I am doing wrong ?
    Thanks,
    Bastien

    You may like to look at the PropertySheet from ControlsFX.
    Not sure if it does what you want, but the concept appears similar.

  • Difference between Java applet and JavaFX

    Hello, all!
    I am studying javaFX in general. As far as I understand there is no main difference between java applet and javafx, except javafx has different syntax and library simple to use. Is it right?

    Basically, yes. But as you point out, it is supposed to be faster to develop in JavaFX...
    For example, Processing allows to export to applet, and is strong on doing graphics, but to see if user has clicked on a circle, you have to check the mouse coordinates against the circle coordinates, or create your own Circle class: it is at a much lower level.
    Likewise, you can use gaming frameworks like Slick2D or PulpCore, but they might be lacking on GUI (but perhaps faster). Or use Apache's Pivot, strong on GUI, but perhaps lacking a bit on graphics and animation.
    It depends on your needs, if you prefer to stick to Java, etc.

  • Package javafx.json and javafx.gui not found

    hi ,
    getting package javafx.json and javafx.gui not found errors.... have the package names changed ,, if so pls tell new names of these packages ......

    Hi Josh,
    thanks for your quick reply. I agree that javafx.gui has been replaced by javafx.scene package.
    But can't find reference to javafx.json package.
    Saw its use on http://blogs.sun.com/clarkeman/entry/javafx_script_and_json_weather .
    I'm trying to pass a json from my java code and use it in my javafx code. But in javafx code it comes as plain string

  • Netbeans and JavaFX

    I am new to Netbeans and am only using it for the JavaFX integration (IntelliJ user) so I am not sure if I am dealing with my ignorance of Netbeans or some JavaFX idiosyncrasy.
    However, when I try to organize my JavaFX code into package structure (rather than using a single default package) and go to run it I get NoClassDef exceptions on my main class. It looks like netbeans automatically packages up the files into a jar and runs it from a jar. I took a peek inside the generated jar and Netbeans is not maintaining the package structure inside the jar it is just putting all the classes at the root of the jar (hence the NoClassDefs).
    How can I get Netbeans to maintain the package structure inside the jar?
    Does JavaFX use the "package" keyword the same way as Java does?

    Yep, after I was able to get my classes in a package structure (rather than default package) I discovered that.
    I couldn't at first get my classes out of the default package. I am spoiled by IntelliJ which changes/adds package statements when you move classes. Netbeans did not automatically add the package statement when I moved from the default package to a package structure. Nor did it warn me that the classes were missing a package statement and/or the package statement didn't match its package location.

  • Alternative to "javafx.io.Resource" and "javafx.io.Storage" in JavaFX 2.2?

    Silverlight has a sandboxed file storage location as well as a facility to store key/value pairs.
    It looks like JavaFX had some similar tools in 1.x, but they appear to be gone in 2.2.
    Can anyone point me toward an alternative for both services?
    Thanks,
    Michael

    Here you go.... I think this is almost reusable as is (my method logging methods need to be removed, and the directory for standalone persistence needs to be changed for your implementation).
    PersistenceApi
    public interface PersistenceApi {
        public InputStream getInputStream(String fileName);
        public boolean createNewFile(String fileName);
        public OutputStream getOutputStream(String fileName);
    }PersistenceManager.... its like a factory, responsible for determining whether or not in Webstart mdoe or not and instantiating the correct implementation of PersistenceApi (not thread safe)
    public class PersistenceManager {
        //static variables
        private static PersistenceApi persistence;
        //public functions
        public static PersistenceApi getPersistenceApi() {
            if (persistence == null) {
                String homeDir = null;
                try {
                    homeDir = System.getProperty(game.CONSTANTS.STANDALONE_INSTALL_DIR_SYSTEM_PROPERTY);
                } catch (SecurityException e) {
                    game.Log.debug("in PersistenceManager.getPersistenceApi, got exception");
                if (homeDir != null) {//...in standalone mode
                    game.Log.debug("in PersistenceManager.getPersistenceApi, in standalone mode, homeDir == " + homeDir);
                    persistence = new StandalonePersistence();
                } else {//...in web start mode
                    game.Log.debug("in PersistenceManager.getPersistenceApi, in web start mode");
                    persistence = new JnlpPersistence();
            return persistence;
    }JnlpPersistence
    public class JnlpPersistence implements PersistenceApi {
        //private variables
        private URL codeBase = null;
        private static PersistenceService persistenceService = null;
        //constructors
        JnlpPersistence() {
            setCodeBase();
            makePersistenceService();
        //private functions
        private void makePersistenceService() {
            if (persistenceService == null) {
                try {
                    persistenceService = (PersistenceService) ServiceManager.lookup("javax.jnlp.PersistenceService");
                } catch (UnavailableServiceException e) {
                    game.Log.debug("in JnlpPersistence.makePersistenceService(), got exception while getting instance of PersistenceService.  " + e.getMessage());
            assert persistenceService != null;
        private void setCodeBase() {
            if (codeBase == null) {
                BasicService bs;
                try {
                    bs = (BasicService) ServiceManager.lookup("javax.jnlp.BasicService");
                    codeBase = bs.getCodeBase();
                } catch (UnavailableServiceException e) {
                    game.Log.debug("in JnlpPersistence.setCodeBase(), got exception while getting codeBase from.  " + e.getMessage());
            assert codeBase != null;
        //public functions
        @Override
        public InputStream getInputStream(String fileName) {
            String thisMethodsName = "in JnlpPersistence.getInputStream(), ";
            URL newFileUrl;
            FileContents newFc;
            try {
                newFileUrl = new URL(codeBase.toExternalForm() + fileName);
                newFc = persistenceService.get(newFileUrl);
                if (newFc == null) {
                    game.Log.debug(thisMethodsName + "filecontents is null for filename = " + fileName);
                    return null;
                if (!newFc.canRead()) {
                    game.Log.debug(thisMethodsName + "filecontents is not readable for filename = " + fileName);
                    return null;
            } catch (Exception e) {
                game.Log.debug(thisMethodsName + "caught exception while getting filecontents for filename = " + fileName + ".  " + e.getMessage());
                return null;
            InputStream is;
            try {
                is = newFc.getInputStream();
            } catch (Exception e) {
                game.Log.debug(thisMethodsName + "caught exception while getting input stream for filename = " + fileName + ".  " + e.getMessage());
                return null;
            return is;
        @Override
        public boolean createNewFile(String fileName) {
            URL newFileUrl;
            try {
                newFileUrl = new URL(codeBase.toExternalForm() + fileName);
                persistenceService.create(newFileUrl, CONSTANTS.MAX_PROFILE_FILE_SIZE);
            } catch (Exception e) {
                game.Log.debug("in JnlpPersistence.createNewFile, got exception while creating file with name = " + fileName + ".  " + e.getMessage());
                return false;
            return true;
        @Override
        public OutputStream getOutputStream(String fileName) {
            String thisMethodsName = "in JnlpPersistence.getOutputStream, ";
            URL newFileUrl;
            FileContents newFc;
            try {
                newFileUrl = new URL(codeBase.toExternalForm() + fileName);
                newFc = persistenceService.get(newFileUrl);
                if (newFc == null) {
                    game.Log.debug(thisMethodsName + "filecontents is null for filename = " + fileName);
                    return null;
                if (!newFc.canWrite()) {
                    game.Log.debug(thisMethodsName + "filecontents is not writeable for filename = " + fileName);
                    return null;
            } catch (Exception ex) {
                game.Log.debug(thisMethodsName + "caught exception while getting filecontents for filename = " + fileName + ".  " + ex.getMessage());
                return null;
            OutputStream os;
            try {
                os = newFc.getOutputStream(true);
            } catch (Exception e) {
                game.Log.debug(thisMethodsName + "caught exception while getting OutputStream for filename = " + fileName + ".  " + e.getMessage());
                return null;
            return os;
    }StandalonePersistence
    public class StandalonePersistence implements PersistenceApi {
        //private variables
        private final String SAVE_DIR = ".tm" + CONSTANTS.PATH_DELIMITTER;
        private String savePath;
        private File savePathFile;
        //constructor
        StandalonePersistence() {
            savePath = System.getProperty(game.CONSTANTS.STANDALONE_INSTALL_DIR_SYSTEM_PROPERTY) + CONSTANTS.PATH_DELIMITTER + SAVE_DIR;
            savePathFile = new File(this.savePath);
            if (savePathFile.exists() == false) {
                savePathFile.mkdir();
        //public functions
        @Override
        public InputStream getInputStream(String fileName) {
            String thisMethod = "in StandalonePersistence.getInputStream, ";
            File file = new File(savePath + CONSTANTS.PATH_DELIMITTER + fileName);
            if (file.exists() == false) {
                game.Log.debug(thisMethod + "file does not exist");
                return null;
            if (file.canRead() == false) {
                game.Log.error(thisMethod + "file is not readable");
                return null;
            InputStream is = null;
            try {
                is = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                game.Log.error(thisMethod + "got exception while getting inputStream. " + e.getMessage());
            return is;
        @Override
        public boolean createNewFile(String fileName) {
            File file = new File(savePath + CONSTANTS.PATH_DELIMITTER + fileName);
            try {
                return file.createNewFile();
            } catch (IOException ex) {
                game.Log.error("in StandalonePersistence.createNewFile, got exception while creating file " + fileName + ".  " + ex.getMessage());
                return false;
        @Override
        public OutputStream getOutputStream(String fileName) {
            String thisMethod = "in StandalonePersistence.getOutputStream, ";
            File file = new File(savePath + CONSTANTS.PATH_DELIMITTER + fileName);
            if (file.exists() == false) {
                game.Log.debug(thisMethod + "file does not exist");
                if (this.createNewFile(fileName) == false) {
                    return null;
                game.Log.debug(thisMethod + "created new file");
            if (file.canWrite() == false) {
                game.Log.error(thisMethod + "file is not writable");
                return null;
            OutputStream os = null;
            try {
                os = new FileOutputStream(file);
            } catch (FileNotFoundException e) {
                game.Log.error(thisMethod + "got exception while getting outputStream. " + e.getMessage());
            return os;
    }Edited by: jmart on Aug 30, 2012 11:17 AM
    Edited by: jmart on Aug 30, 2012 11:20 AM

  • Netbeans 6.9.1 and JavaFX formatter

    Is there any idea why Netbeans 6.9RC1 has a better javafx formatter than 6.9.1?
    I'm always using the formatter with below configuration.
    extend tab to space = no
    all curly brackets are on new line
    Netbeans 6.9 RC1 has deficiency in some points:
    -insert a before a.content[i]
    -i18n strings : ##""
    -in string expressions: "...{some-expression}"
    But Netbeans 6.9.1 has also same bugs. Even worse. My 800 lines of code become 1000 lines when I ran the formatter (adding extra spaces after each keyword).
    I wonder whether the fx team is using the formatter in netbeans. I really ask this not for criticizing. Before 6.9.1, I guessed the problem of formatter was that only small code segments were tested.
    But in 6.9.1, some sample codes in formatter are also wrong formatted.

    Michael Schmid wrote:
    Wohoo,
    starting as a forum newbie....again :s
    Anyway, I've run into some troubles during the setup of my very first J2EE 6 project in Netbeans. I've installed Netbeans 6.9.1 and the included Glassfish v3 server runtime. Then I've created a new J2EE 6 project using Netbeans J2EE project wizard. Said wizard has an option: "Use shared library directory". I ticked this option and specified the shared library directory to be "lib". Then I've added JAR files to it, but somehow this JARs are not added to the classpath of the dependent EJB and Web project. Any time I try to import a class from one of the EAR libraries I get the compile-time ClassNotFound error in the IDE.
    I'm a seasoned Eclipse user, and only recently have switched over to Netbeans (mostly out of curiosity). In Eclipse the ${EarProject}/lib folder was automatically recognized as the EAR's lib folder, and any JAR files added to it where available for all J2EE modules in the EAR project. After consulting the integrated Netbeans help on the topic I was convinced that this should work the same in Netbeans. Can any experienced Netbeans developer assist me in this please?
    PS: I'm sorry if this is the inappropriate forum category, but the old "Netbeans" category from the Sun Forums seems to have disappeared during the forum transition.
    EDIT: on an unrelated note I'd like to bring to your attention that this is the first "real Java question" in this forum :D ("Wohoo this is new" posts don't count)
    Edited by: 791078 on 24.09.2010 18:27You are right, these are the wrong forums. Post your question here: http://forums.netbeans.org/ , if you want help from people who regularly userNetbeans.

  • Integrating Java and JavaFX..?

    Hi
    I am a new bee to JavaFX. I have a Java program which connects to the MySql Databas and fetches the data and prints the data, and also I have written a Java FX program for my GUI. Is there any way for me to integrate these two program so that the data fetched by using the Java program can be used in Javafx. If is there any way plz let me know.
    Or
    Is there any other way for me to connect to the MySql Database through JavaFx
    Edited by: Ajaybvs on Feb 15, 2010 7:35 PM

    It is a common question that have been answered several times on this forum.
    I suggest to try and use the search facilities...
    But in short, in JavaFX you instantiate Java objects as usual (var x = new JavaObject();) and you can use them freely.

  • Netbeans Platform Application and JavaFX CSS API

    I'm using JavaFX in my Netbeans Platform Application. I load JavaFX scene with next code:
    SwingUtilities.invokeLater(new Runnable()
                    @Override
                    public void run()
                        javaFxPanel.setSize(getSize());
                        add(javaFxPanel, BorderLayout.CENTER);
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                    Group branchNode = new Group();
                                    Scene scene = new Scene(branchNode);
                                    try{
                                        scene.getStylesheets().add("C:\\Xlab\\pandora\\branches\\simon-welcome-screen\\TraineeGuiApp\\modules\\ui\\welcomescreen\\main.css");
                                    catch(Exception e)
                                       Exceptions.printStackTrace(e);
                                    Rectangle rect = new Rectangle(100,100);
                                    rect.setLayoutX(50);
                                    rect.setLayoutY(50);
                                    rect.getStyleClass().add("my-rect");
                                    ((Group)scene.getRoot()).getChildren().add(rect);
                                    // Add scene to panel
                                    javaFxPanel.setScene(scene);
                                    javaFxPanel.setVisible(true);
                        //Application.launch(FXApplication.class, null);
                });As you can see i provide absolute path to my css file. CSS file and class that i want to use it from are in same package. I also tried providing just a "main.css" string to scene.getStylesheets().add("main.css"); method.
    I have no idea why this is not working. Any suggestions?
    Edited by: user8867321 on 1.9.2011 9:56

    Admittedly, the stylesheet path handling is pretty bad. If you can see the .css file in your browser, then you have a valid URL. You can also use Class.getResource("blah").toExternalForm() to get the right URL string. For example, if I have my .css file in the same directory as Main.java, then I could do scene.getStylesheets().add(Main.class.getResource("sample.css").toExternalForm());

  • Concurrency and javafx.beans.property

    I am building a MVC architecture and i'd like the model to be running independetly of the view/controller, so the model runs concurrently with the controller/view.
    the following example is a very simplified build on how i have it:
    controller:
    public class controller extends AnchorPane implements Initializable{
         private ObjectProperty<Model> m;
         @FXML Label aLabel;
         public controller() throws Exception{
              this.m = new SimpleObjectProperty<Model>(this, "Model", null);
              FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/View.fxml"));
              fxmlLoader.setController(this);
              fxmlLoader.setRoot(this);
              fxmlLoader.load();
         @Override public void initialize(URL arg0, ResourceBundle arg1){}
         public void setGame(Model m) throws Exception{
              this.m.set(m);
              aLabel.textProperty().bind(this.m.get().getIntProperty().asString());
         public void start(){
              //Method1:
              m.get().start();
              //Method2:
              Task<Void> task = new Task<Void>() {
                   @Override public Void call() {
                        m.get().start();
                        return null;
              new Thread(task).start();
              //Method3:
              m.get().start();     //Model extends Thread and public void start() to protected void run()
              //Method4:
              m.get().start();     //Model extends Task<Void> and
                             //public void start() to protected Void call() throws Exception
              //Method5:          //calling any of the before ones on the controller that calls this one
    }model:
    public class Model extends Thread{
         IntegerProperty intProperty;
         public Model(){
              this.intProperty = new SimpleIntegerProperty(0);
         public IntegerProperty getIntProperty(){
              return intProperty;
         public void start(){
              while (true){
                   this.intProperty.set(this.intProperty.get()+1);
    }Tried any of those and the results are:
    -Method1: the view crashes and cannot be seen anything (model seems to be working since continues in the loop)
    -Method2: when reaches the first this.intProperty.set(this.intProperty.get()+1); the task gets frozen and stops
    -Method3: execution error on this.intProperty.set(this.intProperty.get()+1);
    -Method4: same as Method3
    -Method5: like before ones
    how can i make the it work?

    There are a few things wrong here.
    First, if you want the model to use a Thread, make sure you know how to use the Thread class. There's a decent section on concurrency at the [url http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html]Java tutorial. What you need here is to have your Model class override the run() method, not the start() method. Then call the start() method, which will cause the run() method to be executed on a separate thread of execution. (You may be doing this in Method 3, I couldn't understand your comment.)
    This is probably just an artifact of your simplified version, but your run() method should block at some point. Multiple threads can be executed on the same processor, so your current implementation may hog that processor, making it impossible for the FX Application thread to do its stuff. For testing, throw in a Thread.sleep(...) call, wrapped in a try/catch block for the InterruptedException. I assume that the real application is waiting for something from the server, so there would be some "natural" blocking of the thread in that case.
    The important rule for the UI is that changes to the interface should only be performed on the FX Application thread. Assuming you have the implementation of your model correctly running on a background thread, you violate this with your binding. (The model sets its intProperty on the background thread; the binding causes the label's text to be changed on the same thread.) So to fix this your controller should listen for changes in the model's int property, and schedule a call to aLabel.setText(...) on the FX application thread using Platform.runLater(...). You want to make sure you don't flood the FX Application thread with too many such calls. Depending on how often the int property in the model is getting updated, you may need the techniques discussed in {thread:id=2507241}.
    The Task API from JavaFX provides nice mechanisms to call back to the JavaFX Application thread; however this is not really applicable in this case. The Task class encapsulates a one-off task that (optionally) returns a value and then completes, which is not what you're doing here.
    Here's a complete example; it's not broken out into separate FXML for the view and a controller, etc, but you can see the structure and break it down as you need.
    import javafx.application.Application;
    import javafx.application.Platform;
    import javafx.beans.property.IntegerProperty;
    import javafx.beans.property.SimpleIntegerProperty;
    import javafx.beans.value.ChangeListener;
    import javafx.beans.value.ObservableValue;
    import javafx.event.ActionEvent;
    import javafx.event.EventHandler;
    import javafx.scene.Scene;
    import javafx.scene.control.Button;
    import javafx.scene.control.Label;
    import javafx.scene.layout.AnchorPane;
    import javafx.stage.Stage;
    public class ConcurrentModel extends Application {
      @Override
      public void start(Stage primaryStage) {
        final AnchorPane root = new AnchorPane();
        final Label label = new Label();
        final Model model = new Model();
        model.intProperty.addListener(new ChangeListener<Number>() {
          @Override
          public void changed(final ObservableValue<? extends Number> observable,
              final Number oldValue, final Number newValue) {
            Platform.runLater(new Runnable() {
              @Override
              public void run() {
                label.setText(newValue.toString());
        final Button startButton = new Button("Start");
        startButton.setOnAction(new EventHandler<ActionEvent>() {
          @Override
          public void handle(ActionEvent event) {
            model.start();
        AnchorPane.setTopAnchor(label, 10.0);
        AnchorPane.setLeftAnchor(label, 10.0);
        AnchorPane.setBottomAnchor(startButton, 10.0);
        AnchorPane.setLeftAnchor(startButton, 10.0);
        root.getChildren().addAll(label, startButton);
        Scene scene = new Scene(root, 100, 100);
        primaryStage.setScene(scene);
        primaryStage.show();
      public static void main(String[] args) {
        launch(args);
      public class Model extends Thread {
        private IntegerProperty intProperty;
        public Model() {
          intProperty = new SimpleIntegerProperty(this, "int", 0);
          setDaemon(true);
        public int getInt() {
          return intProperty.get();
        public IntegerProperty intProperty() {
          return intProperty;
        @Override
        public void run() {
          while (true) {
            intProperty.set(intProperty.get() + 1);
            try {
              Thread.sleep(50);
            } catch (InterruptedException exc) {
              exc.printStackTrace();
              break;
    }

Maybe you are looking for

  • Help! I want to trasnfer my DVDs to my ipod video.

    Why is no info out there ont hsi topic. APple introduces a video iPod and I cant for th elife of me figure out how to get a plain old DVD onto my iPod. Can anyone explain this in English for me? Dont get fancy with too many jargon words. Thanks. Basi

  • Which table stores CO Internal Order Status

    Hi Guys,               I am changing Internal Order status, but can't find the respective field in RESB table. AUFK status fields are not even changed ! Any idea Which table records internal order status changes ? Cheers

  • Adobe packages in iPad reader

    Can I read packages in adobe reader?

  • SIP play-out delay

    Dear all, I am having a problem with RTP packets. I have deployed cucm 8.6, and for some reson its response time is very variable even whe I ping the server from inside the vlan. ( there is almost 20% packet loss ). Reply from 192.168.223.100: bytes=

  • IPod 80gb gets and error and/or freezes when trying to sync

    When i try to sync my iPod to my computer, it will go smoothly until about 2-10 gigs of music is on the device, then i will either bet an error message, or itunes will freeze, losing the majority of the music that was just loaded.