How do I make a class in JavaFX 2.0 a usable Node?

2019-07-21 18:33发布

问题:

I am new to JavaFX so please don't hesitate to explain basic concepts. I am able to create a simple GUI and I have a TabPane with two tabs in my program. My question is how do I create a class that can be used as a node?

For example, tab.setContent(stuff) would add stuff to a tab, tab assuming of course that stuff is a Node. So let's say I create a class called Clock and want to add an instance of it to tab, how do I do such a thing?

The clock should be a graphical object. I'm new to graphical programming so references to Swing etc. won't be particularly helpful.

回答1:

In your case, create a class "Clock" and extend it with a layout you wish it to contain. For example:

public class Clock extends BorderPane{}

Then, you can set properties or other Nodes to it by using a constructor.

public class Clock extends BorderPane{
     TextArea ta = new TextArea("This is TOP");
     this.setTop(ta);
     Button b1 = new Button("This is button 1");
     Button b2 = new Button("This is button 2");
     HBox box = new HBox();
     box.getChildren().addAll(b1,b2);
     this.setCenter(box);
}

Then, you would call it from your main program as such:

@Override
public void start(Stage primaryStage){
     primaryStage.setScene(new Scene(new Clock()));
     primaryStage.show();
}

In your case, you would set the Scene when the tab is pressed. That can be done using the Tab class and adding an actionListener to it.

tab.setContent(new Clock());

Hope this helped.



回答2:

Please add a method in clock, then also make a constructor that calls this method. put all

TextArea ta = new TextArea("This is TOP");
 this.setTop(ta);
 Button b1 = new Button("This is button 1");
 Button b2 = new Button("This is button 2");
 HBox box = new HBox();
 box.getChildren().addAll(b1,b2);
 this.setCenter(box);

inside that methode.