Introducing ClockControl

Before adding a new style class, let's start by converting out Clock application into a ClockControl which can be used in any application like other JavaFX nodes.

It will not be a full-fledged Control, but a first step. We'll talk about making a real Controls in Chapter 10, Advanced Controls and Charts.

I've made the following changes in order to prepare for CSS handling:

  • Made the ClockControl class extend BorderPane
  • Moved all graphics initialization to the ClockControl constructor
  • Simplified timing logic; the old one was needed to demonstrate the JavaFX API from Chapter 1, Stages, Scenes, and Layout, and Chapter 2, Building Blocks – Shapes, Text, and Controls.

The following is the resulting source code:

// chapter6/cssapi/ClockControl.java
public class ClockControl extends BorderPane {

private final Text txtTime = new Text();
private final Rotate rotateSecondHand = new Rotate(0, 0, 0);
private final Rotate rotateMinuteHand = new Rotate(0, 0, 0);
private final Rotate rotateHourHand = new Rotate(0, 0, 0);
private final Shape hourHand;

public ClockControl() {
// create minutes hand
Path minuteHand = new Path(
new MoveTo(0, 0),
new LineTo(15, -5),
new LineTo(100, 0),
new LineTo(15, 5),
new ClosePath());
minuteHand.setFill(Color.DARKGRAY);
minuteHand.getTransforms().add(rotateMinuteHand);
minuteHand.setTranslateX(minuteHand.getBoundsInLocal().getWidth()/2);

// create seconds hand
Line secondHand = new Line(0, 0, 90, 0);
secondHand.getTransforms().add(rotateSecondHand);
secondHand.setTranslateX(secondHand.getBoundsInLocal().getWidth()/2);

// create hours hand
hourHand = new Path(
new MoveTo(0, 0),
new LineTo(20, -8),
new LineTo(60, 0),
new LineTo(20, 8),
new ClosePath());
hourHand.setFill(Color.LIGHTGRAY);
hourHand.getTransforms().add(rotateHourHand);
hourHand.setTranslateX(hourHand.getBoundsInLocal().getWidth() / 2);

this.setCenter(new StackPane(minuteHand, hourHand, secondHand));
this.setBottom(txtTime);
BorderPane.setAlignment(txtTime, Pos.CENTER);

Timeline ttimer = new Timeline(new KeyFrame(Duration.seconds(1),
(event) -> {
SimpleDateFormat dt = new SimpleDateFormat("hh:mm:ss");
Date now = new Date();
String time = dt.format(now);

rotateSecondHand.setAngle(now.getSeconds() * 6 - 90);
rotateMinuteHand.setAngle(now.getMinutes() * 6 - 90);
rotateHourHand.setAngle(now.getHours() * 30 - 90);
txtTime.setText(time);
}));
ttimer.setCycleCount(Timeline.INDEFINITE);
ttimer.playFrom(Duration.millis(999));
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.144.194