Wednesday, 28 December 2016

Chapter 16 Exercise 22, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

16.22 (Play, loop, and stop a sound clip) Write a program that meets the following requirements:
■ Get an audio file from the class directory using AudioClip.
■ Place three buttons labeled Play, Loop, and Stop, as shown in Figure 16.46a.
■ If you click the Play button, the audio file is played once. If you click the
Loop button, the audio file keeps playing repeatedly.
If you click the Stop button, the playing stops.


import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.HBox;
import javafx.scene.media.AudioClip;
import javafx.stage.Stage;

public class Exercise_22 extends Application {

    final String URI = "file:/home/ghosthenry/us.mp3";

    @Override
    public void start(Stage primaryStage) throws Exception {

        AudioClip audioClip = new AudioClip(URI);

        Button btPlay = new Button("Play");
        btPlay.setOnAction(e-> {
            if (audioClip.isPlaying()) {
                audioClip.stop();
            }
            audioClip.setCycleCount(1);
            audioClip.play();
        });
        Button btLoop = new Button("Loop");
        btLoop.setOnAction(e-> {
            if (audioClip.isPlaying()) {
                audioClip.stop();
            }
            audioClip.setCycleCount(AudioClip.INDEFINITE);
            audioClip.play();
        });
        Button btStop = new Button("Stop");
        btStop.setOnAction(e -> audioClip.stop());
        HBox hBox = new HBox(btPlay, btLoop, btStop);
        hBox.setSpacing(10);
        hBox.setPadding(new Insets(10));

        primaryStage.setScene(new Scene(hBox));
        primaryStage.setTitle("Play audio");
        primaryStage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

Chapter 16 Exercise 21, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

16.21 (Count-down stopwatch)
Write a program that allows the user to enter time in seconds
in the text field and press the Enter key to count down the seconds,
as shown in Figure 16.45d. The remaining seconds are redisplayed every
one second. When the seconds are expired, the program starts to play
music continuously.


import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.File;

/**
 *
 * (Count-down stopwatch)
 *      Write a program that allows the user to enter time in seconds
 *      in the text field and press the Enter key to count down the seconds,
 *      as shown in Figure 16.45d. The remaining seconds are redisplayed every
 *      one second. When the seconds are expired, the program starts to play
 *      music continuously.
 * Created by luizsa on 9/29/14.
 */
public class Exercise_21 extends Application {

    final String URL = "home/ghosthenry/us.mp3";

    @Override
    public void start(Stage primaryStage) throws Exception {

        TextField tfCountDown = new TextField("0");
        tfCountDown.setFont(Font.font(50));
        tfCountDown.setPrefColumnCount(3);
        tfCountDown.setAlignment(Pos.CENTER);
        tfCountDown.setFocusTraversable(false);
        Pane pane = new Pane(tfCountDown);
        StackPane stackPane = new StackPane(pane);

        Timeline timeline = new Timeline(
                new KeyFrame(Duration.millis(1000), e-> {
                    tfCountDown.setText((Integer.parseInt(tfCountDown.getText()) - 1) + "");
        }));

        tfCountDown.setOnAction(e-> {
            if (timeline.getStatus() == Animation.Status.RUNNING) {
                timeline.stop();
            }
            timeline.setCycleCount(Integer.parseInt(tfCountDown.getText()));
            tfCountDown.setEditable(false);
            timeline.play();
        });

        File file = new File(URL);
        MediaPlayer mediaPlayer = new MediaPlayer(new Media(file.toURI().toString()));

        timeline.setOnFinished(event -> {
            mediaPlayer.play();
        });
        primaryStage.setScene(new Scene(stackPane));
        primaryStage.setTitle("Countdown");
        primaryStage.show();
    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

Chapter 16 Exercise 20, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

16.20 (Count-up stopwatch)
Write a program that simulates a stopwatch,
as shown in Figure 16.45a. When the user
clicks the Start button, the button’s lbl
is changed to Pause, as shown in Figure 16.45b.
When the user clicks the Pause button, the button’s
lbl is changed to Resume, as shown in Figure 16.45c. The
Clear button resets the count to 0 and resets the button’s lbl to Start.


public class StopWatch {

    private long mStartTime;
    private long mEndTime;
    private long mElapsedPause;
    private int mLastSecond = 0;

    private boolean mIsOn;
    private boolean mIsPaused;

    private int mSeconds;
    private int mMinutes;
    private int mHours;

    public StopWatch() {
        mStartTime = System.currentTimeMillis();
    }

    public long getStartTime() {
        return mStartTime;
    }

    public long getEndTime() {
        return mEndTime;
    }

    public void start() {
        mIsOn = true;
        mStartTime = System.currentTimeMillis();
    }

    public void stop(){
        mEndTime = System.currentTimeMillis();
        mIsOn = false;
    }

    public long getElapsedTime() {
        return mEndTime - mStartTime;
    }

    public long peek() {
        return System.currentTimeMillis() - mStartTime;
    }
    public void pause() {
        mIsPaused = true;
        mElapsedPause = System.currentTimeMillis() - mStartTime;
    }

    public void resume() {
        mIsPaused = false;
        mStartTime = System.currentTimeMillis() - mElapsedPause;
    }

    public boolean isOn() {
        return mIsOn;
    }
    public boolean nextSecond() {
        updateTime();
        if (mSeconds != mLastSecond) {
            mLastSecond = mSeconds;
            return true;
        } else {
            return false;
        }
    }
    public boolean nextFiveSeconds() {
        updateTime();
        return mSeconds % 5 == 0;
    }

    public int getHour(){
        updateTime();
        return mHours;
    }

    public int getMinute(){
        updateTime();
        return mMinutes;
    }

    public int getSeconds(){
        updateTime();
        return mSeconds;
    }

    private void updateTime() {

        long currentTime = peek() / 1000;
        mSeconds = (int)(currentTime % 60);
        currentTime = currentTime / 60;

        mMinutes = (int) (currentTime % 60);
        currentTime = currentTime / 60;

        mHours = (int)(currentTime % 24);

    }

    @Override
    public String toString() {

        updateTime();
        String hours = getTimeFormat(mHours);
        String minutes = getTimeFormat(mMinutes);
        String seconds = getTimeFormat(mSeconds);

        return hours + ":" + minutes + ":" + seconds;
    }

    private String getTimeFormat(int time) {
        return (time > 9) ? time + "" : "0" + time;
    }

    public void reset(){
        stop();
        mHours = 0;
        mMinutes = 0;
        mSeconds = 0;
        mStartTime = 0;
        mEndTime = 0;
    }


    public boolean isPaused() {
        return mIsPaused;
    }
}


import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Exercise_20 extends Application {

    StopWatch stopWatch = new StopWatch();
    Label mLabel = new Label("00:00:00");
    @Override
    public void start(Stage primaryStage) {


        Timeline timeline = new Timeline(new KeyFrame(Duration.millis(1000), e-> {
            mLabel.setText(stopWatch.toString());
        }));
        timeline.setCycleCount(Timeline.INDEFINITE);

        // bottom pane
        Button btStartPause = new Button("Start");
        btStartPause.setOnAction(event -> {
            btStartPause.setText((btStartPause.getText().equals("Pause") ? "Start" : "Pause"));
            if (!stopWatch.isOn()) {
                stopWatch.start();
                timeline.play();
            } else
            if (stopWatch.isPaused()) {
                timeline.play();
                stopWatch.resume();
            } else {
                stopWatch.pause();
                timeline.pause();
            }
        });

        Button btClear = new Button("Clear");
        btClear.setOnAction(event -> {
            stopWatch.stop();
            timeline.stop();
            btStartPause.setText("Start");
            mLabel.setText("00:00:00");
        });
        HBox bottomPane = new HBox(btStartPause, btClear);
        bottomPane.setAlignment(Pos.CENTER);
        bottomPane.setSpacing(10);
        bottomPane.setPadding(new Insets(10));
        mLabel.setFont(Font.font(50));

        StackPane centerPane = new StackPane(mLabel);
        centerPane.setPadding(new Insets(10));

        BorderPane borderPane = new BorderPane(centerPane);
        borderPane.setBottom(bottomPane);
        primaryStage.setScene(new Scene(borderPane));
        primaryStage.setTitle("Stopwatch");
        primaryStage.show();

    }

    public static void main(String[] args) {
        Application.launch(args);
    }
}

Chapter 16 Exercise 19, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

16.19 (Control a group of fans)
Write a program that displays three fans in a group, with
control buttons to start and stop all of them, as shown
in Figure 16.44.

import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Exercise_19 extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {

        BorderPane[] borderPanes = new BorderPane[3];
        FanPane[] fanPanes = new FanPane[3];

        for (int i = 0; i < borderPanes.length; i++) {
            fanPanes[i] = new FanPane(100);
            borderPanes[i] = new BorderPane(fanPanes[i]);
            borderPanes[i].setTop(fanPanes[i].hButtons);
            borderPanes[i].setBottom(fanPanes[i].scrollPane);
            borderPanes[i].setStyle("-fx-border-color: black;");
        }

        // center pane
        HBox hFans = new HBox(borderPanes);

        // bottom pane
        Button btStartAll = new Button("Start All");
        btStartAll.setOnAction(e-> {
            for (FanPane fan : fanPanes) {
                if (fan.fanTimeline.getStatus() != Animation.Status.RUNNING) {
                    fan.playPause.fire();
                }
            }
        });
        Button btStopAll = new Button("Stop All");
        btStopAll.setOnAction(e -> {
            for (FanPane fan : fanPanes) {
                if (fan.fanTimeline.getStatus() == Animation.Status.RUNNING) {
                    fan.stop();
                }
            }
        });
        HBox bottomPane = new HBox(btStartAll, btStopAll);
        bottomPane.setSpacing(10);
        bottomPane.setPadding(new Insets(5));

        bottomPane.setAlignment(Pos.CENTER);

        primaryStage.setScene(new Scene(new BorderPane(hFans, null, null, bottomPane, null)));
        primaryStage.setTitle("Fan");
        primaryStage.show();

    }

    public static void main(String[] args) {
        Application.launch(args);
    }

    private class FanPane extends Pane {

        private Circle c;
        private Arc[] blades = new Arc[4];
        private double increment = 1;

        // Buttons
        Button playPause = new Button("Play/Pause");
        Button increase = new Button("Increase");
        Button decrease = new Button("Decrease");
        Button reverse = new Button("Reverse");

        HBox hButtons = new HBox(playPause,increase,decrease, reverse);
        Timeline fanTimeline;

        Slider mSlider = new Slider();
        HBox scrollPane = new HBox(mSlider);


        FanPane(double radius) {
            double w = radius * 4;
            double h = radius * 2;

            setMinWidth(w);
            setMinHeight(h + radius);
            c = new Circle(w/2  , h / 2 + (radius /2), radius, Color.TRANSPARENT);
            c.setStroke(Color.BLACK);

            double bladeRadius = radius * 0.9;
            for (int i = 0; i < blades.length; i++) {
                blades[i] = new Arc(
                        c.getCenterX(), c.getCenterY(), // center point
                        bladeRadius, bladeRadius, // X and Y radius
                        (i * 90) + 30, 35); // start angle and length
                blades[i].setFill(Color.RED);
                blades[i].setType(ArcType.ROUND);
            }

            getChildren().addAll(c);
            getChildren().addAll(blades);


            KeyFrame keyFrame = new KeyFrame(Duration.millis(10), e -> spin());

            fanTimeline = new Timeline(keyFrame);
            fanTimeline.setCycleCount(Timeline.INDEFINITE);

            // Buttons Play/pause, increase, decrease, reverse
            playPause.setOnAction(e -> {
                if (fanTimeline.getStatus() == Animation.Status.RUNNING) {
                    fanTimeline.pause();
                } else {
                    fanTimeline.play();
                }
            });

            increase.setOnAction(e -> {
                fanTimeline.setRate(fanTimeline.getCurrentRate() + 1);
                mSlider.setValue(fanTimeline.getCurrentRate());
            });

            decrease.setOnAction(e -> {
                fanTimeline.setRate(
                        (fanTimeline.getCurrentRate() - 1 < 0) ? 0 : fanTimeline.getCurrentRate() - 1);
                mSlider.setValue(fanTimeline.getCurrentRate());

            });
            mSlider.setMin(0);
            mSlider.setMax(35);
            mSlider.valueProperty().addListener(e -> {
                final double direction = (fanTimeline.getCurrentRate() >= 0) ? 1 : -1;
                fanTimeline.setRate(mSlider.getValue() * direction);
            });
            mSlider.setMinWidth(200);
            scrollPane.setAlignment(Pos.CENTER);
            scrollPane.setPadding(new Insets(5));

            reverse.setOnAction(e -> increment *= -1);
            hButtons.setSpacing(5);
            hButtons.setAlignment(Pos.CENTER);
            hButtons.setPadding(new Insets(2, 2, 2, 2));

        }


        private void spin() {
            for (Arc blade : blades) {
                double prevStartAngle = blade.getStartAngle();
                blade.setStartAngle(prevStartAngle - increment);
            }
        }

        private void stop(){
            fanTimeline.stop();
        }

    }
}

Chapter 16 Exercise 18, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

16.18 (Simulation: a running fan)
Rewrite Programming Exercise 15.28 to
add a slider to control the speed of the fan,
as shown in Figure 16.43c.


import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Arc;
import javafx.scene.shape.ArcType;
import javafx.scene.shape.Circle;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Exercise_18 extends Application {

    public static void main(String[] args) {
        Application.launch(args);
    }

    @Override
    public void start(Stage primaryStage) throws Exception {


        FanPane pane = new FanPane(100);

        BorderPane borderPane = new BorderPane(pane);
        borderPane.setTop(pane.hButtons);
        borderPane.setBottom(pane.scrollPane);
        primaryStage.setScene(new Scene(borderPane));
        primaryStage.setTitle("Fan");
        primaryStage.show();
    }

    private class FanPane extends Pane {

        private Circle c;
        private Arc[] blades = new Arc[4];
        private double increment = 1;

        // Buttons
        Button playPause = new Button("Play/Pause");
        //Button resume = new Button("Resume");
        Button increase = new Button("Increase");
        Button decrease = new Button("Decrease");
        Button reverse = new Button("Reverse");

        //HBox hButtons = new HBox(pause,resume,increase,decrease, reverse);
        HBox hButtons = new HBox(playPause,increase,decrease, reverse);
        Timeline fanTimeline;
        //ScrollBar mScrollBar = new ScrollBar();

        Slider mSlider = new Slider();
        HBox scrollPane = new HBox(mSlider);


        FanPane(double radius) {
            double w = radius * 4;
            double h = radius * 2;

            setMinWidth(w);
            setMinHeight(h + radius);
            c = new Circle(w/2  , h / 2 + (radius /2), radius, Color.TRANSPARENT);
            c.setStroke(Color.BLACK);

            double bladeRadius = radius * 0.9;
            for (int i = 0; i < blades.length; i++) {
                blades[i] = new Arc(
                        c.getCenterX(), c.getCenterY(), // center point
                        bladeRadius, bladeRadius, // X and Y radius
                        (i * 90) + 30, 35); // start angle and length
                blades[i].setFill(Color.RED);
                blades[i].setType(ArcType.ROUND);
            }

            getChildren().addAll(c);
            getChildren().addAll(blades);


            KeyFrame keyFrame = new KeyFrame(Duration.millis(10), e -> spin());

            fanTimeline = new Timeline(keyFrame);
            fanTimeline.setCycleCount(Timeline.INDEFINITE);

            // Buttons pause, resume, increase, decrease, reverse
            playPause.setOnAction(e -> {
                if (fanTimeline.getStatus() == Animation.Status.RUNNING) {
                    fanTimeline.pause();
                } else {
                    fanTimeline.play();
                }
            });

            increase.setOnAction(e -> {
                fanTimeline.setRate(fanTimeline.getCurrentRate() + 1);
                mSlider.setValue(fanTimeline.getCurrentRate());
            });

            decrease.setOnAction(e -> {
                fanTimeline.setRate(
                        (fanTimeline.getCurrentRate() - 1 < 0) ? 0 : fanTimeline.getCurrentRate() - 1);
                mSlider.setValue(fanTimeline.getCurrentRate());

            });
            mSlider.setMin(0);
            mSlider.setMax(35);
            mSlider.valueProperty().addListener(e -> {
                final double direction = (fanTimeline.getCurrentRate() >= 0) ? 1 : -1;
                fanTimeline.setRate(mSlider.getValue() * direction);
            });
            mSlider.setMinWidth(200);
            scrollPane.setAlignment(Pos.CENTER);
            scrollPane.setPadding(new Insets(5));

            reverse.setOnAction(e -> increment *= -1);
            hButtons.setSpacing(10);
            hButtons.setAlignment(Pos.CENTER);
            hButtons.setPadding(new Insets(5, 5, 5, 5));

        }


        private void spin() {
            for (Arc blade : blades) {
                double prevStartAngle = blade.getStartAngle();
                blade.setStartAngle(prevStartAngle - increment);
            }
        }

    }

}