程序小白,希望和大家多交流,共同学习
1.时钟
//画一个详细的钟
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Line;
import javafx.scene.text.Text;
import javafx.scene.shape.Circle;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class MoreClockPane extends Pane
{
private int hour;
private int minute;
private int second;
private double w = 250, h = 250;
//默认为当前时间
public MoreClockPane()
{
setCurrentTime();
paintClock();
}
public void setCurrentTime()
{
Calendar calendar = new GregorianCalendar();
this.hour = calendar.get(Calendar.HOUR_OF_DAY);
this.minute = calendar.get(Calendar.MINUTE);
this.second = calendar.get(Calendar.SECOND);
paintClock();
}
public MoreClockPane(int hour, int minute, int second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
paintClock();
}
public void setHour(int hour)
{
this.hour = hour;
paintClock();
}
public int getHour()
{
return hour;
}
public void setMinute(int minute)
{
this.minute = minute;
paintClock();
}
public int getMinute()
{
return minute;
}
public void setSecond(int second)
{
this.second = second;
paintClock();
}
public int getSecond()
{
return second;
}
public void setW(double w)
{
this.w = w;
paintClock();
}
public double getW()
{
return w;
}
public void setH(double h)
{
this.h = h;
paintClock();
}
public double getH()
{
return h;
}
public void paintClock()
{
getChildren().clear();
double centerX = w / 2.0;
double centerY = h / 2.0;
double radius = Math.min(w, h) * 0.4;
Circle clock = new Circle(centerX, centerY, radius);
clock.setFill(Color.WHITE);
clock.setStroke(Color.BLACK);
super.getChildren().add(clock);
//画秒针刻度线
double sDegree = 2 * Math.PI / 60;
for (int i = 0; i < 60; i++)
{
if (i % 5 != 0)
{
double sxs = centerX + radius * Math.sin(sDegree * i) * 0.95;
double sys = centerY - radius * Math.cos(sDegree * i) * 0.95;
double sxe = centerX + radius * Math.sin(sDegree * i);
double sye = centerY - radius * Math.cos(sDegree * i);
Line line = new Line(sxs, sys, sxe, sye);
super.getChildren().add(line);
}
}
//画分针刻度线,标小时
double mDegree = 2 * Math.PI / 12;
for (int i = 1; i <= 12; i++)
{
double mxs = centerX + radius * Math.sin(mDegree * i) * 0.90;
double mys = centerY - radius * Math.cos(mDegree * i) * 0.90;
double mxe = centerX + radius * Math.sin(mDegree * i);
double mye = centerY - radius * Math.cos(mDegree * i);
double txs = centerX + radius * Math.sin(mDegree * i) * 0.80;
double tys = centerY - radius * Math.cos(mDegree * i) * 0.80 ;
Line line = new Line(mxs, mys, mxe, mye);
Text hText = new Text(txs - 5, tys, i + "");
super.getChildren().addAll(line, hText);
}
//画指针
double sL = radius * 0.8;
double secondX = centerX + sL * Math.sin(second * 2 * Math.PI / 60);
double secondY = centerY - sL * Math.cos(second * 2 * Math.PI / 60);
Line secondLine = new Line(centerX, centerY, secondX, secondY);
secondLine.setStroke(Color.RED);
double mL = radius * 0.65;
double minuteX = centerX + mL * Math.sin(minute * 2 * Math.PI / 60);
double minuteY = centerY - mL * Math.cos(minute * 2 * Math.PI / 60);
Line minuteLine = new Line(centerX, centerY, minuteX, minuteY);
minuteLine.setStroke(Color.BLUE);
double hL = radius * 0.6;
//注意此处 minute 要除以60.0 不是60,还有时钟除以 12
double hourX = centerX + hL * Math.sin((hour + minute / 60.0) * (2 * Math.PI / 12));
double hourY = centerY - hL * Math.cos((hour + minute / 60.0) * (2 * Math.PI / 12));
Line hourLine = new Line(centerX, centerY, hourX, hourY);
hourLine.setStroke(Color.GREEN);
String time = hour + ":" + minute + ":" + second;
Text tTime = new Text(centerX - 23, centerY + 20, time);
super.getChildren().addAll(secondLine, minuteLine, hourLine, tTime);
}
//返回数字时间
public static String getTime()
{
Calendar time = new GregorianCalendar();
return time.get(Calendar.HOUR_OF_DAY) + ":" + time.get(Calendar.MINUTE) + ":" + time.get(Calendar.SECOND);
}
}
//让时钟动起来
//时钟大小可以随桌面改变大小
import javafx.animation.Animation;
import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.util.Duration;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.Label;
import javafx.geometry.Pos;
import javafx.beans.Observable;
import javafx.beans.InvalidationListener;
public class ClockAnimation extends Application
{
@Override
public void start(Stage primaryStage)
{
MoreClockPane clock = new MoreClockPane();
BorderPane pane = new BorderPane();
pane.setCenter(clock);
EventHandler<ActionEvent> eventHandler = new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent e)
{
clock.setCurrentTime();
//从内部类引用的变量必须是最终变量或实际上的最终变量
}};
Timeline animation = new Timeline(new KeyFrame(Duration.millis(1000), eventHandler));
animation.setCycleCount(Timeline.INDEFINITE);
animation.play();
//练习使用事件监听,也可以直接使用上一章的绑定bind()
pane.widthProperty().addListener(new InvalidationListener()
{
@Override
public void invalidated(Observable o)
{
clock.setW(pane.getWidth());
}
});
pane.heightProperty().addListener(new InvalidationListener()
{
@Override
public void invalidated(Observable o)
{
clock.setH(pane.getHeight());
}
});
Scene scene = new Scene(pane);
primaryStage.setTitle("ClockAnimation");
primaryStage.setScene(scene);
primaryStage.show();
}
}
2.反弹的小球
//实现小球自动移动
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<ActionEvent> eventHandler = new EventHandler<ActionEvent>(){
@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);
}
}
//实现鼠标按下小球停止运动,松开继续运动,使用上下键,给小球加速和减速
//可拖拽改变窗体大小,限制小球运动范围
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.input.KeyCode;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.input.KeyEvent;
public class BounceBallControl extends Application
{
@Override
public void start(Stage primaryStage)
{
BallPane ballPane = new BallPane();
ballPane.setOnMousePressed(new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent o)
{
ballPane.pause();
}
});
ballPane.setOnMouseReleased(new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent o)
{
ballPane.play();
}
});
ballPane.setOnKeyPressed(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent ke)
{
if (ke.getCode() == KeyCode.DOWN)
{
ballPane.decreaseSpeed();
}
else if (ke.getCode() == KeyCode.UP)
{
ballPane.increaseSpeed();
}
}
});
Scene scene = new Scene(ballPane, 300, 50);
primaryStage.setTitle("BounceBallControl");
primaryStage.setScene(scene);
primaryStage.show();
ballPane.requestFocus();
}
}
3.通过按钮在Dos界面打印特定文字
//单击按钮,在屏幕打印出信息
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.HBox;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
public class PrintMessage extends Application
{
@Override
public void start(Stage primaryStage)
{
HBox pane = new HBox();
pane.setSpacing(10);
pane.setPadding(new Insets(20, 20, 20, 20));
Button btOK = new Button("OK");
Button btCancel = new Button("Cancel");
btOK.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent e)
{
System.out.println("OK butten clicked.");
}
});
//lambda表达式
btCancel.setOnAction(e -> System.out.println("Cancel button clicked"));
pane.getChildren().addAll(btOK, btCancel);
Scene scene = new Scene(pane);
primaryStage.setTitle("PrintMessage");
primaryStage.setScene(scene);
primaryStage.show();
}
}
4.给之前写的还贷款程序加一个GUI
public class Loan
{
private double annualInterest;
private int numberOfYears;
private double loanAmount;
private java.util.Date loanDate;
public Loan()
{
loanDate = new java.util.Date();
}
public Loan(double annualInterest, int numberOfYears, double loanAmount)
{
this.annualInterest = annualInterest;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
loanDate = new java.util.Date();
}
public double getAnnualInterest()
{
return annualInterest;
}
public int getNumberOfYears()
{
return numberOfYears;
}
public double getLoanAmount()
{
return loanAmount;
}
public void setAnnualInterest(double annualInterest)
{
this.annualInterest = annualInterest;
}
public void setNumberOfYears(int numberOfYears)
{
this.numberOfYears = numberOfYears;
}
public void setLoanAmount(double loanAmount)
{
this.loanAmount = loanAmount;
}
public double getMonthlyPayment()
{
double monthlyInterestRate = annualInterest / 1200;
double monthlyPayment = loanAmount * monthlyInterestRate/ (1 -
(1 / Math.pow(1 + monthlyInterestRate, numberOfYears * 12)));
return monthlyPayment;
}
public double getTotalPayment()
{
double totalPayment = getMonthlyPayment() * numberOfYears * 12;
return totalPayment;
}
public java.util.Date getLoanDate()
{
return loanDate;
}
}
//指定GUI界面计算贷款
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.GridPane;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.geometry.Pos;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
public class CalcualteLoan extends Application
{
private Label lbAnnualInterestRate = new Label("Annual Interest Rate");
private TextField tfAnnualInterestRate = new TextField();
private Label lbNumberOfYears = new Label("Number Of Years");
private TextField tfNumberOfYears = new TextField();
private Label lbLoanAmount = new Label("Loan Amount");
private TextField tfLoanAmount = new TextField();
private Label lbMonthlyPayment = new Label("Monthly Payment");
private TextField tfMonthlyPayment = new TextField();
private Label lbTotalPayment = new Label("Total Payment");
private TextField tfTotalPayment = new TextField();
private Button btCalculate = new Button("Calculate");
@Override
public void start(Stage primaryStage)
{
//确定位置
GridPane pane = new GridPane();
pane.setHgap(5);
pane.setVgap(5);
pane.setPadding(new Insets(20, 20, 20, 20));
pane.add(lbAnnualInterestRate, 0, 0);
pane.add(tfAnnualInterestRate, 1, 0);
pane.add(lbNumberOfYears, 0, 1);
pane.add(tfNumberOfYears, 1, 1);
pane.add(lbLoanAmount, 0, 2);
pane.add(tfLoanAmount, 1, 2);
pane.add(lbMonthlyPayment, 0, 3);
pane.add(tfMonthlyPayment, 1, 3);
pane.add(lbTotalPayment, 0, 4);
pane.add(tfTotalPayment, 1, 4);
pane.add(btCalculate, 1, 5);
//排版,将要计算量设置成不可填写
pane.setAlignment(Pos.CENTER);
tfAnnualInterestRate.setAlignment(Pos.BOTTOM_RIGHT);
tfNumberOfYears.setAlignment(Pos.BOTTOM_RIGHT);
tfLoanAmount.setAlignment(Pos.BOTTOM_RIGHT);
tfMonthlyPayment.setAlignment(Pos.BOTTOM_RIGHT);
tfTotalPayment.setAlignment(Pos.BOTTOM_RIGHT);
tfMonthlyPayment.setEditable(false);
tfTotalPayment.setEditable(false);
GridPane.setHalignment(btCalculate, HPos.RIGHT);
btCalculate.setOnAction(e -> calculateLoanPayment());
Scene scene = new Scene(pane);
primaryStage.setTitle("CalcualteLoan");
primaryStage.setScene(scene);
primaryStage.show();
}
public void calculateLoanPayment()
{
double interest = Double.parseDouble(tfAnnualInterestRate.getText());
int year = Integer.parseInt(tfNumberOfYears.getText());
double loanAmount = Double.parseDouble(tfLoanAmount.getText());
Loan loan = new Loan(interest, year, loanAmount);
tfMonthlyPayment.setText(String.format("$%.2f", loan.getMonthlyPayment()));
tfTotalPayment.setText(String.format("$%.2f", loan.getTotalPayment()));
}
}
5.改变字符串位置(1)
//在面板中鼠标点到哪里字符串就在哪里显示
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.input.MouseButton;
public class ChangeTextPlace extends Application
{
@Override
public void start(Stage primaryStage)
{
Pane pane = new Pane();
Text text = new Text(20, 20, "Programming is fun.");
text.setFont(Font.font("MyFont", FontWeight.BOLD, FontPosture.ITALIC, 20));
pane.getChildren().add(text);
text.setFill(Color.GREEN);
text.setStroke(Color.GREEN);
//注册事件不一样,得到的结果完全不一样
pane.setOnMouseClicked(new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent e)
{
if (e.getButton() == MouseButton.PRIMARY)
{
text.setX(e.getSceneX());
text.setY(e.getSceneY());
}
}
});
Scene scene = new Scene(pane, 400, 400);
//primaryStage.setResizable(false);
primaryStage.setTitle("ChangeText");
primaryStage.setScene(scene);
primaryStage.show();
}
}
6。改变字符串位置(2)
//鼠标拖动text
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.text.Font;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
public class MouseEventDemo extends Application
{
@Override
public void start(Stage primaryStage)
{
Pane pane = new Pane();
Text text = new Text(20, 20, "Programming is fun!");
text.setFont(new Font("MyFont", 20));
text.setStroke(Color.RED);
text.setFill(Color.RED);
pane.getChildren().add(text);
// text.setOnMouseDragged(e -> {
// text.setX(e.getX());
// text.setY(e.getY());
// });
text.setOnMouseDragged(new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent e)
{
text.setX(e.getX());
text.setY(e.getY());
}
});
Scene scene = new Scene(pane, 400, 400);
primaryStage.setTitle("Dragged text");
primaryStage.setScene(scene);
primaryStage.show();
}
}
7.改变小球位置(1)
//使用按键的up/down/left/right移动一个圆
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Circle;
import javafx.scene.control.Label;
import javafx.scene.paint.Color;
import javafx.scene.input.KeyEvent;
import javafx.event.EventHandler;
public class ControlACirle extends Application
{
@Override
public void start(Stage primaryStage)
{
Pane pane = new Pane();
Circle circle = new Circle(10, 10, 10);
circle.setFill(Color.RED);
circle.setStroke(Color.BLACK);
pane.getChildren().add(circle);
circle.setOnKeyPressed(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent e)
{
switch (e.getCode())
{
case UP:
circle.setCenterY(circle.getCenterY() - 10); break;
case DOWN:
circle.setCenterY(circle.getCenterY() + 10); break;
case LEFT:
circle.setCenterX(circle.getCenterX() - 10); break;
case RIGHT:
circle.setCenterX(circle.getCenterX() + 10); break;
}
}
});
Scene scene = new Scene(pane, 200, 200);
primaryStage.setScene(scene);
primaryStage.setTitle("ControlACirle");
primaryStage.show();
circle.requestFocus();
}
}
8.改变小球位置(2)
//使用鼠标的移动来移动一个小球
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;
import javafx.scene.shape.Circle;
import javafx.scene.paint.Color;
public class MoveACircle extends Application
{
@Override
public void start(Stage primaryStage)
{
Pane pane = new Pane();
Circle circle = new Circle(10, 10, 10);
circle.setFill(Color.RED);
circle.setStroke(Color.RED);
pane.getChildren().add(circle);
//由pane注册事件,当鼠标在pane中移动,就会触发事件源,产生事件,此时事件处理器就会
//进行事件处理,处理结果就是移动小球、
pane.setOnMouseMoved(new EventHandler<MouseEvent>()
{
@Override
public void handle(MouseEvent e)
{
circle.setCenterX(e.getX());
circle.setCenterY(e.getY());
}
});
Scene scene = new Scene(pane, 600, 600);
primaryStage.setTitle("MoveACircle");
primaryStage.setScene(scene);
primaryStage.show();
}
}
9.动画(1)
//升国旗
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.shape.Line;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.animation.PathTransition;
import javafx.animation.Timeline;
import javafx.util.Duration;
public class RaseChinaFlag extends Application
{
@Override
public void start(Stage primaryStage)
{
Pane pane = new Pane();
ImageView flag = new ImageView("image/china.gif");
pane.getChildren().add(flag);
Line line = new Line(100, 300, 100, 50);
Rectangle column = new Rectangle(23, 5, 5, 400);
column.setFill(Color.BROWN);
column.setStroke(Color.BLACK);
pane.getChildren().add(column);
PathTransition animation = new PathTransition(Duration.millis(10000), line, flag);
animation.setCycleCount(5);
//动画播放的命令
animation.play();
Scene scene = new Scene(pane, 200, 400);
primaryStage.setTitle("RaseChinaFlag");
primaryStage.setScene(scene);
primaryStage.show();
}
}
10。动画(2)
//闪烁的文字
import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.text.Text;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.layout.Pane;
import javafx.animation.FadeTransition;
import javafx.animation.KeyFrame;
import javafx.util.Duration;
import javafx.animation.Timeline;
import javafx.event.EventHandler;
import javafx.event.ActionEvent;
public class Twinkle extends Application
{
@Override
public void start(Stage primaryStage)
{
Pane pane = new Pane();
Text text = new Text(100, 100, "Programming");
text.setFont(Font.font("MyFont", 25));
//文本字体颜色变换动画
EventHandler<ActionEvent> changeColor = e-> {
Color color = Color.color(Math.random(), Math.random(), Math.random());
text.setFill(color);
text.setStroke(color);
};
Timeline change = new Timeline(new KeyFrame(Duration.millis(4000), changeColor));
change.setCycleCount(Timeline.INDEFINITE);
pane.getChildren().add(text);
//字体透明度变换动画
FadeTransition animation = new FadeTransition(Duration.millis(2000), text);
animation.setFromValue(0.1);
animation.setToValue(1.0);
animation.setCycleCount(Timeline.INDEFINITE);
animation.setAutoReverse(true);
change.play();
animation.play();
Scene scene = new Scene(pane, 400, 200);
primaryStage.setTitle("Twinkle");
primaryStage.setScene(scene);
primaryStage.show();
}
}