r/JavaFX • • Oct 22 '24

Help Custom component in JavaFX(Best practice)

Hello, everyone. A question arose regarding the best practice of creating custom components in JavaFX. For example, we need to draw an atom. An atom contains a nucleus and electrons. What would be the best structure to draw from?

For example:

class Atom extend Pane {

Nuclear nuclear;

List<Electron> electrons;

}

class Nuclear extend Circle {}

class Electron extend Circle {}

Would it be best practice for the aggregator component to inherit from the container (in this case JavaFX Pane)? Is it possible to wrap the nucleus and electron in a container(Nuclear extend Pane) better?

I would be grateful for any tips

6 Upvotes

15 comments sorted by

View all comments

Show parent comment

1

u/sedj601 Oct 23 '24 edited Oct 23 '24

In my implementation, I use the following nodes. Label -> It is text to show the proton and neutron count. "P: 1 N: 1". I created a StackPane. I added a circle to represent the nucleus, and I added the label on top. Next, I added the electrons as circles and their orbits dynamically based on the number of electrons in the constructor's input. I then animate the orbits using PathTransitions.

Here is how my code starts.

    private final IntegerProperty widthProperty = new SimpleIntegerProperty(300);
    private final IntegerProperty heightProperty = new SimpleIntegerProperty(300);
    private final StringProperty protonNumber = new SimpleStringProperty("0");
    private final StringProperty neutronNumber = new SimpleStringProperty("0");  
    private final DoubleProperty angle = new SimpleDoubleProperty(0);
    
    private final Label nucleusText = new Label("P: " + protonNumber.getValue() + " N: " + neutronNumber.getValue());
    private final Circle nucleus = new Circle(30, Color.ORANGE);    
    
    
    public Atom(int numberOfProtons, int numberOfNeutrons, int numberOfElectrons) {