猿问

javafx,我如何从主进程获取值

这基本上是一个简单的生产者-消费者应用程序。代码示例如下:


public class MyMainClass extends Application {


    // blocking queue that will be shared among my prcesses

    BlockingQueue bq;


    public static void main(String[] args) {

        launch(args);

    }


    @Override

    public void start(Stage primaryStage) {

        primaryStage.setTitle("Hello World!");


        // parameters I wont the Thread passes to the server socket

        TextArea parameters = new TextArea("parameters-for-the-server");


        // setting the Producer button

        Button btnProducer = new Button();

        btnProducer.setText("Start Producer");

        btnProducer.setOnAction(new EventHandler<ActionEvent>() {


            @Override

            public void handle(ActionEvent event) {


              /* ReadSocket connects to a web sockets, 

                reads strings and saves them into a shared blocking queue: bq*/

                ReadSocket rs = new ReadSocket(bq);

                new Thread(rs).start();

            }

            // setting the Consumer button

            Button btnConsumer = new Button();

            btnConsumer.setText("Start Consumer");

            btnConsumer.setOnAction(new EventHandler<ActionEvent>() {


                @Override

                public void handle(ActionEvent event) {


                  /* ReadSocket connects to a web sockets, 

                    reads strings and saves them into a shared blocking queue: bq*/

                    Consumer c = new Consumer(bq);

                    new Thread(c).start();

                }

        });


        StackPane root = new StackPane();

        root.getChildren().add(btn);

        primaryStage.setScene(new Scene(root, 300, 250));

        primaryStage.show();

    }

}

我的教授说,如果我希望它们可用于其他对象,我应该在构造函数中传递值。


我ReadSocket应该看起来像这样:


public class ReadSocket{

  BlockingQueue bq;


  ReadSocket(bq){

    this.bq = bq;

    // more code

  }


那么,这是否意味着我必须传递我的价值观,例如:


ReadSocket rs = new ReadSocket(bq, parameters.getText()); 即使ReadSocket不是直接使用它们而是基于parameters? 这样做正确吗?还有其他更好的方法吗?


守着星空守着你
浏览 106回答 1
微课
1回答

蛊毒传说

有两种方法可以做到这一点。一个使用constructor和其他使用setter method。但是正如您提到的,您的教授建议您使用构造函数传递参数,以便其他对象可以使用这些参数。只要确保您存储对通过构造函数传递的参数的引用public class ReadSocket{&nbsp; BlockingQueue bq;&nbsp; String parameters;&nbsp; ReadSocket(BlockingQueue bq, String parameters)&nbsp; {&nbsp; &nbsp; this.bq = bq;&nbsp; &nbsp; this.parameters = parameters;&nbsp; }&nbsp; private void createOtherObjects()&nbsp; {&nbsp; &nbsp; MyObject o = new MyObjext(this.parameters);&nbsp; &nbsp; MyServer ms = new MyServer(o);&nbsp; }}
随时随地看视频慕课网APP

相关分类

Java
我要回答