Java语言程序设计 第十六章 (样例代码)

程序小白,希望和大家多交流,共同学习

井字游戏

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.shape.Ellipse;

public class TicTacTurn extends Application
{
    private char whoseTurn = 'X';
    private Cell[][] cell = new Cell[3][3];

    private Label lblStatus = new Label("X's turn to play");

    @Override
    public void start(Stage primaryStage)
    {
        GridPane pane = new GridPane();
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                pane.add(cell[i][j] = new Cell(), j, i);
            }
        }

        BorderPane borderPane = new BorderPane();
        borderPane.setCenter(pane);
        borderPane.setBottom(lblStatus);

        Scene scene = new Scene(borderPane, 450, 170);
        primaryStage.setTitle("TicTacToe");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public boolean isFull()
    {
        for (int i = 0; i < 3; i++)
        {
            for (int j = 0; j < 3; j++)
            {
                if (cell[i][j].getToken() == ' ')
                {
                    return false;
                }
            }
        }
        return true;
    }

    public boolean isWon(char token)
    {
        for (int i = 0; i <  3; i++)
        {
            if (cell[i][0].getToken() == token &&
                cell[i][1].getToken() == token &&
                cell[i][2].getToken() == token)
            {
                return true;
            }
        }

        for (int j = 0; j < 3; j++)
        {
            if (cell[0][j].getToken() == token &&
                cell[1][j].getToken() == token &&
                cell[2][j].getToken() == token)
            {
                return true;
            }
        }

        if (cell[0][0].getToken() == token &&
            cell[1][1].getToken() == token &&
            cell[2][2].getToken() == token)
        {
            return true;
        }

        if (cell[0][2].getToken() == token &&
            cell[1][1].getToken() == token &&
            cell[2][1].getToken() == token)
        {
            return true;
        }

        return false;
    }

    //An inner class for cell
    public class Cell extends Pane
    {
        private char token = ' ';

        public Cell()
        {
            setStyle("-fx-border-color: black");
            this.setPrefSize(2000, 2000);
            this.setOnMouseClicked(e -> handleMouseClick());
        }

        public char getToken()
        {
            return token;
        }

        public void setToken(char c)
        {
            this.token = c;

            if (token == 'X')
            {
                Line line1 = new Line(10, 10, this.getWidth() - 10, this.getHeight() - 10);
                line1.endXProperty().bind(this.widthProperty().subtract(10));
                line1.endYProperty().bind(this.heightProperty().subtract(10));

                Line line2 = new Line(10, this.getHeight() - 10, this.getWidth() - 10, 10);
                line2.startYProperty().bind(this.heightProperty().subtract(10));
                line2.endXProperty().bind(this.widthProperty().subtract(10));

                this.getChildren().addAll(line1, line2);
            }

            else if (token == 'O')
            {
                Ellipse ellipse = new Ellipse(this.getWidth() / 2, this.getHeight() / 2,
                    this.getWidth() / 2 - 10, this.getHeight() / 2 - 10);

                ellipse.centerXProperty().bind(this.widthProperty().divide(2));
                ellipse.centerYProperty().bind(this.heightProperty().divide(2));

                ellipse.radiusXProperty().bind(this.widthProperty().divide(2).subtract(10));
                ellipse.radiusYProperty().bind(this.heightProperty().divide(2).subtract(10));

                ellipse.setStroke(Color.BLACK);
                ellipse.setFill(Color.WHITE);

                getChildren().add(ellipse);
            }
        }

        public void handleMouseClick()
        {
            if (token == ' ' && whoseTurn != ' ')
            {
                setToken(whoseTurn); 
            }

            if (isWon(whoseTurn))
            {
                lblStatus.setText(whoseTurn + "won! The game is over.");
                whoseTurn = ' ';
            }

            else if (isFull())
            {
                lblStatus.setText("Draw! The game is over.");
                whoseTurn = ' ';
            }
            else
            {
                whoseTurn = (whoseTurn == 'X') ? 'O' : 'X';
                lblStatus.setText(whoseTurn + "'s tuen.");
            }
        }
    }
}

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.control.RadioButton;
import javafx.scene.paint.Color;
import javafx.geometry.Insets;
import javafx.scene.control.ContentDisplay;
import javafx.scene.image.ImageView;

public class RadioButtonDemo extends Application
{
    @Override
    public void start(Stage primaryStage)
    {
        StackPane pane = new StackPane();
        RadioButton rbUS = new RadioButton("US");
        rbUS.setGraphic(new ImageView("image/usIcon.gif"));
        rbUS.setTextFill(Color.GREEN);
        rbUS.setContentDisplay(ContentDisplay.LEFT);
        rbUS.setStyle("-fx-border-color: black");
        rbUS.setSelected(true);
        rbUS.setPadding(new Insets(5, 5, 5, 5));
        pane.getChildren().add(rbUS);

        Scene scene = new Scene(pane);
        primaryStage.setTitle("RadioButtonDemo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Ellipse;

public class LabelWithGraphic extends Application
{
    @Override
    public void start(Stage primaryStage)
    {
        ImageView us = new ImageView(new Image("image/us.gif"));
        Label lb1 = new Label("US\n50 States", us);
        lb1.setStyle("-fx-border-corlor: green; -fx-border-width: 2");
        lb1.setContentDisplay(ContentDisplay.BOTTOM);
        lb1.setTextFill(Color.RED);

        Label lb2 = new Label("Circle", new Circle(50, 50, 25));
        lb2.setContentDisplay(ContentDisplay.TOP);
        lb2.setTextFill(Color.ORANGE);

        Label lb3 = new Label("Rectangle", new Rectangle(10, 10, 50, 25));
        lb3.setContentDisplay(ContentDisplay.RIGHT);

        Label lb4 = new Label("Ellipse", new Ellipse(50, 50, 50, 25));
        lb4.setContentDisplay(ContentDisplay.LEFT);

        Ellipse ellipse = new Ellipse(50, 50, 50, 25);
        ellipse.setStroke(Color.GREEN);
        ellipse.setFill(Color.WHITE);
        StackPane stackPane = new StackPane();
        stackPane.getChildren().addAll(ellipse, new Label("Javafx"));
        Label lb5 = new Label("A pane inside a label", stackPane);
        lb5.setContentDisplay(ContentDisplay.BOTTOM);

        HBox pane = new HBox(20);
        pane.getChildren().addAll(lb1, lb2, lb3, lb4, lb5);

        Scene scene = new Scene(pane, 450, 150);
        primaryStage.setTitle("LabelWithGraphic");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;

public class ButtonDemo extends Application
{
    protected Text text = new Text(50, 50, "JavaFX Programming");

    protected BorderPane getPane()
    {
        HBox paneForButton = new HBox(20);
        Button btLeft = new Button("Left", new ImageView("image/left.gif"));
        Button btRight = new Button("right", new ImageView("image/right.gif"));
        paneForButton.getChildren().addAll(btLeft, btRight);
        paneForButton.setAlignment(Pos.CENTER);
        paneForButton.setStyle("-fx-border-color: red");

        BorderPane pane = new BorderPane();
        pane.setBottom(paneForButton);

        Pane paneForText = new Pane();
        paneForText.getChildren().add(text);
        pane.setCenter(paneForText);

        btLeft.setOnAction(e -> text.setX(text.getX() - 10));
        btRight.setOnAction(e -> text.setX(text.getX() + 10));

        return pane;
    }

    @Override
    public void start(Stage primaryStage)
    {
        Scene scene = new Scene(getPane(), 450, 200);
        primaryStage.setTitle("ButtonDemo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.geometry.Insets;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.RadioButton;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.control.ContentDisplay;

public class CheckBoxDemo extends ButtonDemo
{
    @Override
    protected BorderPane getPane()
    {
        BorderPane pane = super.getPane();

        Font fontBoldItalic = Font.font("Times New Roman", FontWeight.BOLD, FontPosture.ITALIC, 20);
        Font fontBold = Font.font("Times New Roman", FontWeight.BOLD, FontPosture.REGULAR, 20);
        Font fontItalic = Font.font("Times New Roman", FontWeight.NORMAL, FontPosture.ITALIC, 20);
        Font fontNormal = Font.font("Times New Roman",FontWeight.NORMAL, FontPosture.REGULAR, 20);

        text.setFont(fontNormal);

        VBox paneForCheckBoxs = new VBox(20);
        paneForCheckBoxs.setPadding(new Insets(5, 5, 5, 5));
        paneForCheckBoxs.setStyle("-fx-border-color: green");
        CheckBox chkBold = new CheckBox("Bold");
        CheckBox chkItalic = new CheckBox("Italic");
        paneForCheckBoxs.getChildren().addAll(chkBold, chkItalic);
        pane.setRight(paneForCheckBoxs);

        EventHandler eventHandler = e ->{
            if (chkBold.isSelected() && chkItalic.isSelected())
            {
                text.setFont(fontBoldItalic);
            }
            else if (chkBold.isSelected())
            {
                text.setFont(fontBold);
            }
            else if (chkItalic.isSelected())
            {
                text.setFont(fontItalic);
            }
            else 
                text.setFont(fontNormal);
        };

        chkBold.setOnAction(eventHandler);
        chkItalic.setOnAction(eventHandler);

        return pane;
    }

    @Override
    public void start(Stage primaryStage)
    {
        Scene scene = new Scene(getPane(), 450, 200);
        primaryStage.setTitle("ButtonDemo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
import javafx.geometry.Insets;
import javafx.scene.control.RadioButton;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.scene.Scene;

public class NewRadioButtonDemo extends CheckBoxDemo
{
    @Override
    protected BorderPane getPane()
    {
        BorderPane pane = super.getPane();

        VBox paneForRadioButtons = new VBox(20);
        paneForRadioButtons.setPadding(new Insets(5, 5, 5, 5));
        paneForRadioButtons.setStyle("-fx-border-width: 2px;-fx-border-color: green");

        RadioButton rbRed = new RadioButton("Red");
        RadioButton rbGreen = new RadioButton("Green");
        RadioButton rbBlue = new RadioButton("Blue");
        RadioButton rbBlack = new RadioButton("Black");
        paneForRadioButtons.getChildren().addAll(rbRed, rbGreen, rbBlue,rbBlack);
        pane.setLeft(paneForRadioButtons);

        //没有分组的话,这些按钮将是独立的。
        //那么选择其中一个的时候,就要将其他的选项设置为未选择。
        ToggleGroup group = new ToggleGroup();
        rbRed.setToggleGroup(group);
        rbGreen.setToggleGroup(group);
        rbBlue.setToggleGroup(group);
        rbBlack.setToggleGroup(group);

        rbRed.setOnAction(e -> {
            if (rbRed.isSelected())
            {
                text.setFill(Color.RED);
            }
        });

        rbGreen.setOnAction(e -> {
            if (rbGreen.isSelected())
            {
                text.setFill(Color.GREEN);
            }
        });

        rbBlue.setOnAction(e -> {
            if (rbBlue.isSelected())
            {
                text.setFill(Color.BLUE);
            }
        });

        rbBlack.setOnAction(e -> {
            if (rbBlack.isSelected())
            {
                text.setFill(Color.BLACK);
            }
        });

        return pane;
    }

    @Override
    public void start(Stage primaryStage)
    {
        Scene scene = new Scene(getPane(), 450, 200);
        primaryStage.setTitle("ButtonDemo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;

public class TextFieldDemo extends NewRadioButtonDemo
{
    @Override
    protected BorderPane getPane()
    {
        BorderPane pane = super.getPane();

        BorderPane paneForTextField = new BorderPane();
        paneForTextField.setPadding(new Insets(5, 5, 5, 5));
        paneForTextField.setStyle("-fx-border-color: green");
        paneForTextField.setLeft(new Label("Enter a new message: "));

        TextField tf = new TextField();
        tf.setAlignment(Pos.BOTTOM_RIGHT);
        paneForTextField.setCenter(tf);
        pane.setTop(paneForTextField);

        tf.setOnAction(e -> {
            super.text.setText(tf.getText());
        });

        return pane;
    }

    @Override
    public void start(Stage primaryStage)
    {
        Scene scene = new Scene(getPane(), 450, 200);
        primaryStage.setTitle("ButtonDemo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
//显示一个图片

package listView.Description;

import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.TextArea;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.text.Font;

public class DescriptionPane extends BorderPane
{
    private Label lbImageTitle = new Label();
    private TextArea taDescription = new TextArea();

    public DescriptionPane()
    {
        lbImageTitle.setContentDisplay(ContentDisplay.TOP);
        lbImageTitle.setPrefSize(200, 200);

        lbImageTitle.setFont(new Font("SansSerif", 16));
        taDescription.setFont(new Font("Serif", 14));

        taDescription.setWrapText(true);
        taDescription.setEditable(false);

        ScrollPane scrollPane = new ScrollPane(taDescription);

        setLeft(lbImageTitle);
        setCenter(scrollPane);
        setPadding(new Insets(5, 5, 5, 5));
    }

    public void setTitle(String title)
    {
        lbImageTitle.setText(title);
    }

    public void setImageView(ImageView icon)
    {
        lbImageTitle.setGraphic(icon);
    }

    public void setDescription(String text)
    {
        taDescription.setText(text);
    }
}
package listView.ComboBoxDemo;

import listView.Description.DescriptionPane;
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.Label;
import javafx.scene.control.ComboBox;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;

public class ComboBoxDemo_2 extends Application
{
    private String[] flagTitles = {"Canada", "China", "Denmark", "France", "Germany",
        "India", "Norway", "United Kingdom", "United States of America"};

    private ImageView[] flagImage = {new ImageView("image/ca.gif"), new ImageView("image/china.gif"),
        new ImageView("image/denmark.gif"), new ImageView("image/fr.gif"), new ImageView("image/germany.gif"),
        new ImageView("image/india.gif"), new ImageView("image/norway.gif"), new ImageView("image/uk.gif"),
        new ImageView("image/us.gif")};

    private String[] flagDescription =new String[9];

    private DescriptionPane descriptionPane = new DescriptionPane();

    private ComboBox cbo = new ComboBox<>();
    //ComboBox 定义的是一个范类型。范类型T为保存在一个组合框中的元素指定元素类型。

    @Override
    public void start(Stage primaryStage)
    {
        flagDescription[0] = "The Canada national flag...";
        flagDescription[1] = "Description for China...";
        flagDescription[2] = "Description for Denmark...";
        flagDescription[3] = "Description for France...";
        flagDescription[4] = "Description for Germany...";
        flagDescription[5] = "Description for India...";
        flagDescription[6] = "Description for Norway...";
        flagDescription[7] = "Description for UK...";
        flagDescription[8] = "Description for US...";

        setDisplay(0);

        BorderPane pane = new BorderPane();

        BorderPane paneForComboBox = new BorderPane();
        paneForComboBox.setLeft(new Label("Select a country: "));
        paneForComboBox.setCenter(cbo);
        pane.setTop(paneForComboBox);
        cbo.setPrefWidth(400);
        cbo.setValue("Canada");

        ObservableList items = FXCollections.observableArrayList(flagTitles);
        cbo.getItems().addAll(items);
        //cbo.setItems(items);
        pane.setCenter(descriptionPane);

        cbo.setOnAction(e -> {
            setDisplay(items.indexOf(cbo.getValue()));
            //items是ObservableList的一个对象,ObservableList是List子接口,
            //使用List类中的indexOf()找到指定元素的索引。使用ComboBox的getValue()
            //返回组合框中选中的值
        });

        Scene scene = new Scene(pane, 500, 170);
        primaryStage.setTitle("ComboBoxDemo_2");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public void setDisplay(int index)
    {
        descriptionPane.setTitle(flagTitles[index]);
        descriptionPane.setImageView(flagImage[index]);
        descriptionPane.setDescription(flagDescription[index]);
    }
}
//ListView使用例子

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.collections.FXCollections;
import javafx.scene.control.ListView;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.SelectionMode;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.FlowPane;

public class ListViewDemo extends Application
{
    private String[] flagTitles = {"Canada", "China", "Denmark", "France", "Germany",
        "India", "Norway", "United Kingdom", "United States of America"};

    private ImageView[] ImageViews = {new ImageView("image/ca.gif"), new ImageView("image/china.gif"),
        new ImageView("image/denmark.gif"), new ImageView("image/fr.gif"), new ImageView("image/germany.gif"),
        new ImageView("image/india.gif"), new ImageView("image/norway.gif"), new ImageView("image/uk.gif"),
        new ImageView("image/us.gif")};

    @Override
    public void start(Stage primaryStage)
    {
        ListView lv = new ListView<>(FXCollections.observableArrayList(flagTitles));
        lv.setPrefSize(200, 200);//Node中的prefHeight(height : double),prefWidth(width : double)
        lv.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);//设置成允许多选

        FlowPane imagePane = new FlowPane(10, 10);
        BorderPane pane = new BorderPane();
        pane.setLeft(new ScrollPane(lv));
        pane.setCenter(imagePane);

        lv.getSelectionModel().selectedItemProperty().addListener(ov -> {
            imagePane.getChildren().clear();
            for (Integer i : lv.getSelectionModel().getSelectedIndices())
            {
                imagePane.getChildren().add(ImageViews[i]);
            }
            //按住ctrl再选择,用来多选
        });

        Scene scene = new Scene(pane, 450, 170);
        primaryStage.setTitle("ListViewDemo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
//ScrollBar滚动条的使用
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.geometry.Orientation;
import javafx.scene.control.ScrollBar;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;

public class ScrollBarDemo extends Application
{
    @Override
    public void start(Stage primaryStage)
    {
        Text text = new Text(20, 20, "JavaFX Programming");

        ScrollBar sbHorizontal = new ScrollBar();
        ScrollBar sbVertical = new ScrollBar();
        sbVertical.setOrientation(Orientation.VERTICAL);

        Pane paneForText = new Pane();
        paneForText.getChildren().add(text);

        BorderPane pane = new BorderPane();
        pane.setCenter(paneForText);
        pane.setBottom(sbHorizontal);
        pane.setRight(sbVertical);

        sbHorizontal.valueProperty().addListener(e -> {
            text.setX(sbHorizontal.getValue() * paneForText.getWidth() / sbHorizontal.getMax());
        });

        sbVertical.valueProperty().addListener(e -> {
            text.setY(sbVertical.getValue() * paneForText.getHeight() / sbVertical.getMax());
        });

        Scene scene = new Scene(pane, 450, 170);
        primaryStage.setTitle("ScrollBarDemo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
//Slider滑动条例子
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.geometry.Orientation;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;

public class SliderDemo extends Application
{
    @Override
    public void start(Stage primaryStage)
    {
        Text text = new Text(20, 20, "JavaFX Programming");
        Slider slHorizontal = new Slider();
        slHorizontal.setShowTickLabels(true);
        slHorizontal.setShowTickMarks(true);

        Slider slVertical = new Slider();
        slVertical.setOrientation(Orientation.VERTICAL);
        slVertical.setShowTickLabels(true);
        slVertical.setShowTickMarks(true);
        slVertical.setValue(100);

        Pane paneForText = new Pane();
        paneForText.getChildren().add(text);

        BorderPane pane = new BorderPane();
        pane.setCenter(paneForText);
        pane.setBottom(slHorizontal);
        pane.setRight(slVertical);

//      slHorizontal.valueProperty().addListener(ov -> {
//          text.setX(slHorizontal.getValue() * paneForText.getWidth() / slHorizontal.getMax());
//      });
//
//      slVertical.valueProperty().addListener(ov -> {
//          text.setY(slVertical.getValue() * paneForText.getHeight() / slVertical.getMax());
//      });

        text.xProperty().bind(slHorizontal.valueProperty().multiply(paneForText.widthProperty()).
            divide(slHorizontal.maxProperty()));

        text.yProperty().bind(slVertical.maxProperty().subtract(slVertical.valueProperty()).
            multiply(paneForText.heightProperty().divide(slVertical.maxProperty())));
        //垂直滑动条的值从上到下是递减的。
        //数值是按照比例划分的

        Scene scene = new Scene(pane, 450, 170);
        primaryStage.setTitle("SliderDemo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
//实现小球自动移动
import javafx.application.Application;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import javafx.util.Duration;
import javafx.scene.shape.Circle;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.beans.property.DoubleProperty;

public class BallPane extends Pane
{
    private final double radius =  20;
    private double x = radius;
    private double y = radius;
    private double dx = 1, dy = 1;
    private Circle circle = new Circle(x, y, radius);
    private Timeline animation;

    public BallPane()
    {
        circle.setFill(Color.GREEN);
        super.getChildren().add(circle);

        EventHandler eventHandler = new EventHandler(){
        @Override
        public void handle(ActionEvent e)
        {
            moveBall();
        }};

        animation = new Timeline(
            new KeyFrame(Duration.millis(50), eventHandler));
        animation.setCycleCount(Timeline.INDEFINITE);
        animation.play();
    }

    public void play()
    {
        animation.play();
    }

    public void pause()
    {
        animation.pause();
    }

    public void increaseSpeed()
    {
        animation.setRate(animation.getRate() + 0.1);
    }

    public void decreaseSpeed()
    {
        animation.setRate(animation.getRate() > 0 ? animation.getRate() - 0.1 : 0);
    }

    public DoubleProperty rateProperty()
    {
        return animation.rateProperty();
    }

    public void moveBall()
    {
        if (x < radius || x > super.getWidth() - radius)
        {
            dx *= -1;
        }
        if (y < radius || y > super.getHeight() - radius)
        {
            dy *= -1;
        }

        x += dx;
        y += dy;
        circle.setCenterX(x);
        circle.setCenterY(y);
    }
}
//使用Slider控制小球运行的速度
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;

public class BounceBallSlider extends Application
{
    @Override
    public void start(Stage primaryStage)
    {
        BallPane ballPane = new BallPane();
        Slider slSpeed = new Slider();
        slSpeed.setMax(20);
        ballPane.rateProperty().bind(slSpeed.valueProperty());

        BorderPane pane = new BorderPane();
        pane.setCenter(ballPane);
        pane.setBottom(slSpeed);

        Scene scene = new Scene(pane, 250, 200);
        primaryStage.setTitle("BounceBallSlider");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
//http://video.eastday.com/a/180223173746612230288.html?qid=hao123lsp
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Region;//这个面板是什么?
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.util.Duration;

public class MediaDemo extends Application
{
    private static final String MEDIA_URL =
        "http://119.188.38.13/677537D848C4C839022C8D4195/0300020200566C319C3A2B08F7C91";

    @Override
    public void start(Stage primaryStage)
    {
        Media media = new Media(MEDIA_URL);
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        MediaView mediaView = new MediaView(mediaPlayer);

        Button playButton = new Button(">");
        playButton.setOnAction(e -> {
            if (playButton.getText().equals(">"))
            {
                mediaPlayer.play();
                playButton.setText("||");
            }
            else
            {
                mediaPlayer.pause();
                playButton.setText(">");
            }
        });

        Button rewindButton = new Button("<<");
        rewindButton.setOnAction(e -> {
            mediaPlayer.seek(Duration.ZERO);
        });

        Slider slVolume = new Slider();
        slVolume.setPrefWidth(150);
        slVolume.setMaxWidth(Region.USE_PREF_SIZE);//这是什么?
        slVolume.setMinWidth(30);
        slVolume.setValue(50);
        mediaPlayer.volumeProperty().bind(slVolume.valueProperty().divide(100));

        HBox hBox = new HBox(10);
        hBox.setAlignment(Pos.CENTER);
        hBox.getChildren().addAll(playButton, rewindButton, new Label("Volume"), slVolume);

        BorderPane pane = new BorderPane();
        pane.setCenter(mediaView);
        pane.setBottom(hBox);

        Scene scene = new Scene(pane, 650, 500);
        primaryStage.setTitle("MediaDemo");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.image.ImageView;
import javafx.scene.image.Image;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.collections.ObservableList;
import javafx.collections.FXCollections;
import javafx.geometry.Pos;

public class FlagAnthem_02 extends Application
{
    private final static int NUMBER_OF_NATIONS = 7;
    private final static String URLBase = "http://cs.armstrong.edu/liang/common";
    private int currentIndex = 0;

    @Override
    public void start(Stage primaryStage)
    {
        Image[] images = new Image[NUMBER_OF_NATIONS];
        MediaPlayer[] mp = new MediaPlayer[NUMBER_OF_NATIONS];

        for (int i = 0; i < NUMBER_OF_NATIONS; i++)
        {
            images[i] = new Image(URLBase + "/image/flag" + i + ".gif");
            mp[i] = new MediaPlayer(new Media(URLBase + "/audio/anthem/anthem" + i + ".mp3"));
        }

        Button btPlayPause = new Button("||");
        btPlayPause.setOnAction(e -> {
            if (btPlayPause.getText().equals(">"))
            {
                btPlayPause.setText("||");
                mp[currentIndex].pause();
            }
            else
            {
                btPlayPause.setText(">");
                mp[currentIndex].play();
            }
        });

        ImageView imageView = new ImageView(images[currentIndex]);
        ComboBox cboNation = new ComboBox<>();
        ObservableList items = FXCollections.observableArrayList(
            "Denmark", "Germany", "China", "India", "Normay", "UK", "US");
        cboNation.getItems().addAll(items);
        cboNation.setValue(items.get(0));
        cboNation.setOnAction(e -> {
            mp[currentIndex].stop();
            currentIndex = items.indexOf(cboNation.getValue());
            imageView.setImage(images[currentIndex]);
            mp[currentIndex].play();
        });

        HBox hBox = new HBox(10);
        hBox.getChildren().addAll(btPlayPause, new Label("Select a nation"), cboNation);
        hBox.setAlignment(Pos.CENTER);

        BorderPane pane = new BorderPane();
        pane.setCenter(imageView);
        pane.setBottom(hBox);

        Scene scene = new Scene(pane, 350, 270);
        primaryStage.setTitle("FlagAnthem");
        primaryStage.setScene(scene);
        primaryStage.show();
    }
}

你可能感兴趣的:(JavaFX)