can I run a javafx from main thread thread?

EDIT: what I want the code for:
(1) controller class
-runs in the background
-creates shopping cart
-create listeners for applications that will add items to your basket
-regulates which application has access to the screen
(2) class ShoppingCart
-runs in the background
-receive the items of no Java-based applications
-stores these items "in the basket.
(3) class checkout
-GUI for the user to remove items in their cart
-complete the transaction before returning control to your cart

I'm new to javafx - and haven't used Java over the years, namely, I'm trying the following:

-------------------------------------------------------------------------------------------------------------------------------
Controller class
-------------------------------------------------------------------------------------------------------------------------------
public class Controller {
     private static ShoppingCart shoppingCart;

     public static void main(String[] args) {
          ExecutorService exec = Executors.newFixedThreadPool(5);
          try {
               shoppingCart = new ShoppingCart(2001);
               exec.execute(shoppingCart);
          } catch (IOException ex) {
               ex.printStackTrace();
          }
     }
}
-------------------------------------------------------------------------------------------------------------------------------
Class ShoppingCart
-------------------------------------------------------------------------------------------------------------------------------
public class ShoppingCart extends Stage implements Runnable {
     private ServerSocket serverSocket;
     private Socket clientSocket;
     private Socket socket;
     private final int port;
     
     private BufferedReader bReader;
     private BufferedWriter bWriter;
     
     private final ArrayList<String> items = new ArrayList<Item>();

    public ShoppingCart(int port) throws IOException {
          this.port = port;
    }
     
     /*
      * when an item arrives at the port, pass the port through to RecieveItem to digest the incomming stream
      */
    @Override
    public void run() {
          
          boolean addMoreItems = true;
          try {
               this.serverSocket = new ServerSocket(port);
          } catch (IOException ex) {
               ex.printStackTrace();
          }
          try {
               while(addMoreItems){
                    this.clientSocket = serverSocket.accept();
                    String theItem = receiveItem(clientSocket);
                    if(theItem == null)
                         addMoreItems = false;
                    else
                         this.items.add(theItem);
               }
          } catch (IOException ex) {
               ex.printStackTrace();
          }
    }

    private String receiveItem(Socket socket) throws IOException {
          String readLine = "";
          String itemString = "";
          
          this.socket = socket;
          this.bReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
          
          while(readLine != null){
               readLine = bReader.readLine();
               // if we are finished adding items, proceed to checkout
               if(readLine.equalsIgnoreCase("checkout")) {
                    // show cart for user to see items before paying
                    itemString = null;
               } else { // otherwise, add the item
                    itemString += "|" + readLine;
               }
          }
          
          return itemString;
     }
-------------------------------------------------------------------------------------------------------------------------------
When I try to run the code, I get the following:
-------------------------------------------------------------------------------------------------------------------------------
Exception in thread "main" java.lang.IllegalStateException: Not on FX application thread; currentThread = main
-------------------------------------------------------------------------------------------------------------------------------

So, is this possible? What Miss me?
Thanks for reading my questions :)
Dave.

Published by: 1003225 on 29 April 2013 20:26

Published by: 1003225 on April 30, 2013 12:49

I did some research and aparently you must republish the same answer for me to be able to show your answer as being correct (for some reason, it is not editable)

Answer:

You can launch an application Java to the main thread by calling Application.launch, but you can call it only once per process or an exception will be thrown:
http://docs.Oracle.com/JavaFX/2/API/JavaFX/application/application.html#launch%28Java.lang.class, %20java.lang.String...%29

---------

Partners:

The cycle of life and the management of threads that run user by the JavaFX application code is documented in the javadoc for JavaFX Application:
http://docs.Oracle.com/JavaFX/2/API/JavaFX/application/application.html

Conditions of application output is kept by Platform.setImplicitExit:
http://docs.Oracle.com/JavaFX/2/API/JavaFX/application/platform.html#setImplicitExit%28boolean%29

Tags: Java

Similar Questions

  • How can I do to block the main thread when to display a dialog box

    I have a problem to block the user interface main thread when to display a dialog box (the dialog was created by the main Application), and when the dialog box is closed, the main Application can go to the next step.
    Here is my code:

    SerializableAttribute public class TitledPaneExample extends Application {}
    instance of TitledPaneExample private;
    StackPane mainModalDimmer;

    /*
    * (non-Javadoc)
    *
    * @see javafx.application.Application #start (javafx.stage.Stage)
    */
    @Override
    public void start (point primaryStage) bird Exception {}
    instance = this;
    primaryStage.setTitle (this.getClass () m:System.NET.SocketAddress.ToString ());

    final StackPane layerPane = new StackPane();
    layerPane.setDepthTest (DepthTest.DISABLE);
    layerPane.setStyle ("background - fx - color: BLACK ;"); ")

    Vb VBox = new VBox();
    vb.setStyle ("background - fx - color: BLUE ;"); ")
    vb.getChildren () .add new (Label ("1"));
    vb.getChildren () .add (Label ("2")) new;
    vb.getChildren () .add new (Label ("3"));
    vb.getChildren () .add (Label ("4")) new;

    Bt1 button = new Button ("bt1");
    BT1.setOnAction (new EventHandler < ActionEvent > () {}
    {} public void handle (ActionEvent event)
    System.out.println ("bt1 trying to the new dialog box > > >");
    Dialogue di = new dialog box (instance, "some trick here!");
    System.out.println ("bt1 dialogue again successfully, try to show");
    di. Show();
    System.out.println ("bt1 dialog hide? < < < < ");"
    }
    });
    vb.getChildren () .add (bt1).

    layerPane.getChildren () .add (vb);

    mainModalDimmer = new StackPane();
    mainModalDimmer.setId ("MainModalDimmer");
    mainModalDimmer.setMaxSize (Double.MAX_VALUE, Double.MAX_VALUE);
    mainModalDimmer.setVisible (false);
    mainModalDimmer.setStyle ("background - fx - color: RED ;"); ")
    layerPane.getChildren () .add (mainModalDimmer);

    Scene sc = new scene (layerPane, 800, 600);
    primaryStage.setResizable (true);
    primaryStage.setScene (sc);
    primaryStage.show ();

    }

    /**
    * Display the node given as a floating dialog on the entire application, with
    * the rest of the application grayed out and blocked from mouse events.
    *
    @param message
    */
    {} public void showModalMessage (message from node)
    mainModalDimmer.getChildren () .add (message);
    mainModalDimmer.setOpacity (0);
    mainModalDimmer.setVisible (true);
    mainModalDimmer.setCache (true);
    TimelineBuilder
    . Create()
    () .keyFrames
    new KeyFrame (Duration.seconds (1),)
    new EventHandler < ActionEvent > () {}
    {} public void handle (ActionEvent t)
    mainModalDimmer.setCache (false);
    }
    }, new KeyValue (mainModalDimmer
    . opacityProperty(), 1.
    Interpolator.EASE_BOTH))) infrastructure)
    . Play();
    }

    /**
    Hide the any modal message that appears
    */
    public void hideModalMessage() {}
    mainModalDimmer.setCache (true);
    TimelineBuilder
    . Create()
    () .keyFrames
    new KeyFrame (Duration.seconds (1),)
    new EventHandler < ActionEvent > () {}
    {} public void handle (ActionEvent t)
    mainModalDimmer.setCache (false);
    mainModalDimmer.setVisible (false);
    mainModalDimmer.getChildren () .clear ();
    }
    }, new KeyValue (mainModalDimmer
    . opacityProperty(), 0,.
    Interpolator.EASE_BOTH))) infrastructure)
    . Play();
    }

    /**
    @param args
    */
    Public Shared Sub main (String [] args) {}
    Launch();
    }

    Dialogue/public class extends TitledPane {}
    private owner of TitledPaneExample = null;
    instance of TitledPane private;

    Dialogue (owner of TitledPaneExample, String message) {}
    This.Owner = owner;
    this.parentThreand = Thread.currentThread ();
    This.instance = this;
    this.setExpanded (true);
    this.setText ("Dialog");
    this.setMaxWidth (400);
    this.setPrefWidth (300);
    this.setMinWidth (200);

    Label the tx = new Label ("message");
    tx.setTooltip (new Tooltip (message));
    tx.setWrapText (true);
    tx.setContentDisplay (ContentDisplay.LEFT);

    Bt button = new Button ("OK");
    bt.setOnAction (new EventHandler < ActionEvent > () {}
    {} public void handle (ActionEvent event)
    masquer();
    }
    });

    Sp ScrollPane = new ScrollPane();
    sp.setHbarPolicy (ScrollBarPolicy.AS_NEEDED);
    sp.setVbarPolicy (ScrollBarPolicy.AS_NEEDED);
    sp.setContent (tx);

    Hb HBox = new HBox (30);
    hb.setPrefHeight (40);
    hb.setAlignment (Pos.CENTER_RIGHT);
    hb.getChildren () .add (bt);

    BP BorderPane = new BorderPane();
    bp.setCenter (sp);
    bp.setBottom (hb);

    this.setContent (bp);
    }

    {} public void show()
    System.out.println ("dialogue show() 1 > > >");

    owner.showModalMessage (instance);

    System.out.println ("dialogue show() 2 > > >");

    }

    public void masquer() {}
    System.out.println ("dialogue masquer() 1 > > >");
    this.owner.hideModalMessage ();

    System.out.println ("dialogue masquer() 2 > > >");
    }
    }

    }

    I'm also interested in how to do this without the use of a step.

    But, if you are ready to use a step for this, you can create a useful first step (without borders) with its owner being your current stage. Then, you can call the function showAndWait on stage that allows to block the thread of your application. For example, I implemented a DialogStage like this:

    package hs.mediasystem.util;
    
    import javafx.animation.KeyFrame;
    import javafx.animation.KeyValue;
    import javafx.animation.Timeline;
    import javafx.event.EventHandler;
    import javafx.scene.effect.ColorAdjust;
    import javafx.stage.Modality;
    import javafx.stage.Stage;
    import javafx.stage.StageStyle;
    import javafx.stage.Window;
    import javafx.stage.WindowEvent;
    import javafx.util.Duration;
    
    public class DialogStage extends Stage implements Dialog {
    
      public DialogStage() {
        super(StageStyle.TRANSPARENT);
    
        this.setTitle("MediaSystem-dialog");
    
        initModality(Modality.APPLICATION_MODAL);
      }
    
      protected void setParentEffect(Stage parent) {
        ColorAdjust colorAdjust = new ColorAdjust();
    
        Timeline fadeOut = new Timeline(
          new KeyFrame(Duration.ZERO,
            new KeyValue(colorAdjust.brightnessProperty(), 0)
          ),
          new KeyFrame(Duration.seconds(1),
            new KeyValue(colorAdjust.brightnessProperty(), -0.5)
          )
        );
    
        parent.getScene().getRoot().setEffect(colorAdjust);
    
        fadeOut.play();
      }
    
      protected void removeParentEffect(Stage parent) {
        parent.getScene().getRoot().setEffect(null);
      }
    
      protected void recenter() {
        Window parent = getOwner();
    
        sizeToScene();
    
        setX(parent.getX() + parent.getWidth() / 2 - DialogStage.this.getWidth() / 2);
        setY(parent.getY() + parent.getHeight() / 2 - DialogStage.this.getHeight() / 2);
      }
    
      @Override
      public final void showDialog(final Stage parent, boolean synchronous) {
        initOwner(parent);
    
        setParentEffect(parent);
    
        setOnShown(new EventHandler() {
          @Override
          public void handle(WindowEvent event) {
            recenter();
            onShow();
          }
        });
    
        if(synchronous) {
          showAndWait();
        }
        else {
          show();
        }
      }
    
      protected void onShow() {
      }
    
      @Override
      public void close() {
        removeParentEffect((Stage)getOwner());
        super.close();
      }
    }
    
  • can I run ms word from an external ssd

    My new Imac takes forever to load programs. Can I use MS Office and Adobe CC leave an external ssd?

    When you install programs, you can specify the location of drive and the directory of the installation. However, an SSD may speed up things a bit, but the time to load application is more memory and hard drive that dependent dependent processor. Which iMac model you have and how much memory is installed? In addition, stop your virus protection if everything is running and all programs running in the background.

  • can I run secure money from Kaspersky 2016 on Fire Fox

    10 showing orange attention, windows-based secure money off as an extension not signed. What should I do?

    42 of Firefox would not disable a due extension this extension is not signed. [Currently scheduled to be implemented in Firefox 45.]
    Firefox 39-plus provides a relative to the extension not be ' checked ' message and said to "act with caution". If it is not available or cannot be activated in the Addons Manager, or it does not, it may be not compatible for other reasons.

  • I can't run videos on websites like you tube using a macbook pro after installing firefox 3.6.15

    I have a macbook pro. Firefox has performed well for years, but after downloading firefox 3.6.15 I can't run all videos from web sites like you tube or Itunes.

    Loading the web page, but the video window does not show at the top, nor all the controls

    When I tried to run a trailer since Itunes sound was there but not the video.

    My pluins are up-to-date.

    I had the same problem and it seems that Adobe Flash Player 10.2 is the culprit. Back this version and everything seems to work properly again.

  • panels and multithreading - what features can I call from another thread.

    I am writing a program (Windows XP, LabWindows/CVI 2010) that has several threads. The main thread generates and manages most of the panels, but not all. Is there a list of what control panel functions are thread-safe and which are not? Reading the help file and the different positions, the functions of set value are safe; game-attribute functions are NOT. (I found that calling (SetPanelAttribute) with ATTR_TITLE will be locked permanently a program!). What about calliing a command callback function? (Via the CallCntrlCallback() function). It seems to work very well so far, but I can't find anything definitive.

    I do a lot of multi-thread applications, so I have a few ideas for you.  Unfortunately, I have not tried to do many of the changes of attributes specific threads lower panel.

    I'm very careful about how I handle the wire "solidity", dealing with the variables in an asynchronous way, as much as possible, to avoid the use of blocking and incorrect values of the variables.

    But there are certainly many things simply cannot make you the son of the daughter.  Things like question popups and launch other threads cannot be done simply.  As long as you understand that the best place to do something is in the main thread, and then a girl thread can use PostDeferredCall (...), do something in the main thread

    In the thread of your daughter, you can insert this call:

    PostDeferredCall (launchNewThread, 0);

    And then this call performs this function in the main thread:
    void CVICALLBACK launchNewThread(void *callbackData)

    {
    CmtScheduleThreadPoolFunction (threadPoolHandle, NewThread, NULL, NULL);
    }

    Or you can insert calls from parameter of the attribute panel inside the function above, I suppose, to safely run in the main thread.

    Hoe, that helps...

    -Gary

  • MenuItems run() method that is called from the thread eventdispatching?

    Hello

    is it? I know that MenuItem itself extends thread, but I wonder why this method is called run() and finally and above all it would'nt be worse if this method would be called from a Thread.

    THX

    In fact the menu items are run on the thread of the event. You can see this by creating a menu item long-term. The menu will not close and will not refresh the screen.

  • Network management operations can be run on the event thread?

    Hello

    I am building a HttpRequestDispatcher class. Is it true that you should performs no operation networking on the thread of the event? Currently, my HttpRequestDispatcher class creates a new thread to run on, however I'm looking to do it either threads...

    Thank you!

    Quote from the HttpConnection API

    "An application will lock if an implementation of this interface opens a connection from main event in the thread.

    You must start another thread to perform your HttpConnection. There are some examples in the samples of the plugin or JDE directory. Check under device samples, blackberry folder, then the folder browser.

  • Why almost all javafx methods must be called from the thread of the application?

    I have a pretty big 3D scene that is refreshed every few seconds.

    It takes a while to update the scene, and I wanted to do it in a background thread.

    Problem is that almost every approach I take requires the application-fx thread.

    Now, I understand that change the UI itself must be called in the application thread, so I tried a different approach:

    Create a new group, add all the nodes (which takes the greatest amount of time) and update the component root of the view with the new group.

    I assumed that only the last party required the application thread, but alas this was not the case.

    group.getChildren () .add also requires that the thread of the application. Why?

    node.setLayoutX () also requires that the thread of the application. Why?

    It is a new set of nodes that are not visible and groups yet, so why can't do this in a background thread?

    The reasons of principle (I think) that JavaFX is mainly a single toolbox threaded are described in:

    https://weblogs.Java.net/blog/2004/10/19/multithreaded-toolkits-failed-dream

    That said, if you manipulate objects that are not part of an active scene, then it should work.  The dream that failed has what to do with the components who participate actively in the molten, interactive GUI.  If you're interacting with only the components out of the screen, then it (should be) without issue.

    Please, create and post an example minimum, executable that replicates the question.

    (Please ensure that the example is minimal and executable).

    In addition, what is the cause as your application "takes some time to update the scene?  Computers are today quite incredibly fast.  Of course, there are valid reasons for some things take time, I wonder what these are in your case.  What is the time?  If your executable example can include something reasonably representative of what you're done which shows something that will take "some time", would be great.

    What you have described so far, I feel that, even if there is no problems with threads, your proposed approach would not fix your performance problem.

  • Running the thread of the child until the end even after that the main thread is terminated

    I run a background task by using the task and the Service Api. When the main application creates little son, the main thread can be terminated without completing the child thread. Is this possible. Thank you.

    Find out about the son of the devil.

    Multithreading - what is Daemon thread in java - Stack Overflow

    Read also the

    Application section of the lifecycle in the javadoc.

  • How can I remove an email from a conversation thread?

    Employees often use ' answer to "a pre-arrival message when you start a new topic. This is to locate the new difficult message later, because in appears under an unrelated conversation thread. Is it possible to delete a message to an existing thread, so that it becomes the first message in a new conversation?

    I have played around with it for awhile now and have received confusing results. Sometimes, delete the contents of the references header does remove a message from a thread, sometimes not. In other cases, change all the references by adding for example a figure at the beginning of the string works, other times it doesn't. By changing the full source, you can modify additional headers, but so far I have not found a consistent method.

    There is more information on the threads here:

    http://KB.mozillazine.org/Stop_threading_by_subject

  • How can I remove my name from the top right of the screen. I have a 2015 13 "MacBook Pro running 10.11.4

    How can I remove my name from the top right of the screen. I have a 2015 13 "MacBook Pro running 10.11.4

    At the top right of the menu bar shows the current user who is logged in and allows quick change of user accounts.

    You can disable the display of menu bar in system preferences > users and groups. Or order just drag it out of the bar.

  • How can I selectively transfer files from an iMac 2009 to a new iMac in 2015? The two running os 10.11

    How can I selectively transfer files from an iMac 2009 to a new iMac in 2015? The two running os 10.11.3.

    I do it with a G4 OS Tiger and the Mavericks MacBook by plugging into an Ethernet jack on my router and by enabling the sharing of files on the G4 in System Preferences > sharing.  If items are placed in a folder called 'Public', it can be read by anyone on the network by logging in as a guest. Otherwise, if I login with my user ID on this computer I get access read/write for all of my folders.

  • Satellite M30X-129: recovery CD can be run from an external drive?

    My wifi seems to have packed - recognizes nearby wireless networks but does not connect to them - so I will try to use the recovery disk product in the hope that it will bring back wifi.

    However, the DVD Multi drive does not work - light flashes to indicate some sort of activity, but no drive appears in my computer. I think that if I buy the external drive, I can run the product recovery disc for this.
    Is the drive Toshiba external DVD SuperMulti (PA3454U-1DV2) compatible with the Satellite M30X - 129 P - M 735? Product recovery can be run from an external drive (bootable?)?

    Any advice would be greatly appreciated!

    Hello

    According to this page of Toshiba, the drive is compatible with your device:
    e http://EU.computers.Toshiba-Europe.com/cgi-bin/ToshibaCSG/options_and_accessories_search_by_model.jsp?servic = 1 = us & selSeries & selFamily = 2326 & SelCategorie = 2319 & family = 2326 & selP roduct = 98795

    The fact is that only the boot device options available: USB-drive floppy/disk HARD/ODD/LAN
    I know you can only boot from external CD/DVD drive if the device supports this option and the unit.
    In my opinion be100% sure you should ask ASP for advice.

    But know one other question: do you have you boot from the restore CD to recover the operating system?
    If you want to recover the operating system, you have to start on this CD and do not run it under Windows. Check it out

  • How can I remove my photos from my iPhone while keeping in iCloud? because I'm running out of space on my iPhone.

    How can I remove my photos from my iPhone while keeping in iCloud? because I'm running out of space on my iPhone.

    I want to keep all my photos in iCloud. I want to remove some of them from my iPhone 4 (IOS 8) in order to free up space on my iPhone. How can I do this? Thanks for help.

    With iCloud library enabled, you cannot delete a photo on a device (or iCloud.com) without deleting each device which uses iCloud photo library (iCloud.com). In order to save space on your mobile devices (and indeed your Mac if you want to) turn on the optimization of the pictures on these devices (settings > photos & camera > optimize storage on your mobile device and Photo preferences > optimize storage on your Mac)

    Dynamic optimization, it reduces the resolution of your photos, if necessary, so that you don't notice it occurring initially. However, when necessary, it is very effective, and users have reported libraries being optimized for much less than 10% of their original size in some cases. My own library is about 9% of its original on my phone size.

Maybe you are looking for