程序小白,希望和大家多交流,共同学习 16.10
//显示文本 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.Button; import javafx.scene.paint.Color; import javafx.scene.layout.VBox; import javafx.scene.layout.HBox; import javafx.scene.text.Text; import java.util.Scanner; import java.io.File; import javafx.geometry.Pos; public class ShowText extends Application { Text text = new Text(); @Override public void start(Stage primaryStage) { //创建输入文件位置的文本域,和启动按钮 HBox hbInputPath = new HBox(10); hbInputPath.setStyle("-fx-border-color: black"); TextField tfPath = new TextField(); tfPath.setPrefColumnCount(20); tfPath.setAlignment(Pos.BOTTOM_RIGHT); Button btView = new Button("View"); hbInputPath.getChildren().addAll(new Label("FileName:"), tfPath, btView); //为文本添加滚动条 ScrollPane cp = new ScrollPane(text); //排版 VBox pane = new VBox(cp, hbInputPath); pane.setPrefSize(400, 400); pane.setAlignment(Pos.BOTTOM_CENTER); //实现按钮事件 btView.setOnAction(e -> { if (!tfPath.getText().equals(null)) { String path = tfPath.getText(); File file = new File(path); if (file.exists()) { try { write(file); } catch (Exception ex) { text.setText(ex.getMessage()); } } else text.setText("This file not exist!"); } }); Scene scene = new Scene(pane); primaryStage.setTitle("ShowText"); primaryStage.setScene(scene); primaryStage.show(); } public void write(File file) throws Exception { Scanner input = new Scanner(file); text.setText(null); while (input.hasNext()) { text.setText(text.getText() + "\n" + input.nextLine()); } } }16.11
//柱状图面板 import javafx.scene.shape.Rectangle; import javafx.scene.shape.Line; import javafx.scene.text.Text; import javafx.scene.paint.Color; import javafx.scene.layout.Pane; import java.util.Arrays; import javafx.scene.control.ScrollPane; public class Histogram extends Pane { private int[] counts; private Rectangle[] rectangles; private Text[] texts; private Line underLine; private double perH = 1.0;//字母每多一个,柱状图增高2像素 private double perW = 10.0;//每个柱子的宽度 private double interval = 10.0;//柱子之间的间隔 public Histogram() { counts = new int[26]; Arrays.fill(counts, 0); rectangles = new Rectangle[26]; texts = new Text[26]; for (int i = 0; i < 26; i++) { rectangles[i] = new Rectangle(0, 0, 0, 0); char ch = (char)('A' + i); texts[i] = new Text("" + ch); } underLine = new Line(0, 0, (perW + interval) * 26, 0); paintHistogram(); } public void setCounts(int[] counts) { this.counts = counts; paintHistogram(); } public void paintHistogram() { getChildren().clear(); //确定高度 int maxNum = getMax(); //System.out.println(maxNum); double maxH = maxNum * perH; //画线 underLine.setStartY(maxH); underLine.setEndY(maxH); //画矩形 //标字母,使用text for (int i = 0; i < 26; i++) { rectangles[i].setX(i * (perW + interval)); rectangles[i].setY(maxH - counts[i] * perH); rectangles[i].setWidth(perW); rectangles[i].setHeight(counts[i] * perH); rectangles[i].setFill(Color.WHITE); rectangles[i].setStroke(Color.BLACK); texts[i].setX(i * (perW + interval)); texts[i].setY(maxH + 10); //System.out.println(i); } this.getChildren().addAll(rectangles); this.getChildren().add(underLine); this.getChildren().addAll(texts); } public int getMax() { int max = counts[0]; for (int i = 1; i < 26; i++) { if (counts[i] > max) { max = counts[i]; } } return max; } } //显示一篇英语文章中各个字母出现的次数的柱状图 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.control.ScrollPane; import javafx.scene.layout.HBox; import javafx.scene.layout.BorderPane; import javafx.geometry.Pos; import javafx.geometry.Insets; import java.util.Scanner; import java.io.File; import java.util.Arrays; public class CountLetterNumbers extends Application { private TextField tfPath = new TextField(); private int[] counts = new int[26]; private Histogram histogram = new Histogram(); @Override public void start(Stage primaryStage) { tfPath.setPrefColumnCount(20); tfPath.setAlignment(Pos.BOTTOM_RIGHT); ScrollPane sc = new ScrollPane(histogram); Button view = new Button("View"); view.setOnAction(e -> { paintHistogram(); }); HBox hbForView = new HBox(10); hbForView.setAlignment(Pos.CENTER); hbForView.getChildren().addAll(new Label("File name"), tfPath, view); BorderPane pane = new BorderPane(); pane.setCenter(sc); pane.setPadding(new Insets(10, 10, 10, 10)); pane.setBottom(hbForView); Scene scene = new Scene(pane); primaryStage.setTitle("CountLetterNumbers"); primaryStage.setScene(scene); primaryStage.show(); } public void paintHistogram() { try { //Arrays.fill(counts, 50); counts = getCounts(); } catch (Exception ex) { System.out.println(ex.toString()); } histogram.setCounts(counts); } //统计字母个数 public int[] getCounts() throws Exception { int[] counts = new int[26]; Arrays.fill(counts, 0); File file = new File(tfPath.getText()); if (file.isFile()) { Scanner input = new Scanner(file); while (input.hasNext()) { String str = input.next(); int length = str.length(); //System.out.println(length); for (int i = 0; i < length; i++) { char ch = str.charAt(i); if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) //Character.isLetter()不能区分汉字和字母 { //System.out.println(ch + " " + i); counts[Character.toUpperCase(ch) - 'A']++; } } } } else tfPath.setText("Wrong file name!!"); System.out.println(Arrays.toString(counts)); return counts; } } //F:\java\java语言程序设计\第十六章\TwoCircles.java16.12
//文本输出的设置 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.CheckBox; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.scene.layout.BorderPane; import javafx.geometry.Pos; import javafx.event.EventHandler; import javafx.event.ActionEvent; import java.io.File; import java.util.Scanner; public class PrintText extends Application { private TextArea ta = new TextArea(); private TextField tf = new TextField(); @Override public void start(Stage primaryStage) { tf.setAlignment(Pos.BOTTOM_RIGHT); tf.setPrefColumnCount(20); Button btView = new Button("View"); HBox hbForTf = new HBox(10); hbForTf.setAlignment(Pos.CENTER); hbForTf.getChildren().addAll(new Label("file name:"), tf, btView); ScrollPane sp = new ScrollPane(ta); //添加复选按钮 HBox hbForChk = new HBox(10); hbForChk.setAlignment(Pos.CENTER); CheckBox chkEditable = new CheckBox("Editable"); chkEditable.setSelected(false); CheckBox chkWrap = new CheckBox("Wrap"); chkWrap.setSelected(true); hbForChk.getChildren().addAll(chkEditable, chkWrap); //这只文本框的功能 btView.setOnAction(e -> { printFile(chkWrap.isSelected()); }); //设置复选框的功能 EventHandler<ActionEvent> handler = e -> { if (chkEditable.isSelected()) { ta.setEditable(true); } else ta.setEditable(false); printFile(chkWrap.isSelected()); }; chkEditable.setOnAction(handler); chkWrap.setOnAction(handler); //排版 BorderPane pane = new BorderPane(); pane.setTop(hbForTf); pane.setCenter(sp); pane.setBottom(hbForChk); Scene scene = new Scene(pane); primaryStage.setResizable(false); primaryStage.setTitle("PrintText"); primaryStage.setScene(scene); primaryStage.show(); } public void printFile(boolean wrap) { ta.setText(null); try { //System.out.println("firstTrue"); String fileName = tf.getText(); File file = new File(fileName); Scanner input = new Scanner(file); //System.out.println("filenameTrue"); if (!tf.getText().equals(null) && file.isFile()) { //System.out.println("fileTrue"); if (wrap) { while (input.hasNext()) { String str = input.nextLine(); ta.setText(ta.getText() + "\n" + str); } } else { while (input.hasNext()) { String str = input.nextLine(); ta.setText(ta.getText() + str); } } } else tf.setText("wrong file name!"); } catch (Exception ex) { tf.setText("Exception"); } } } //F:\java\java语言程序设计\第十六章\ShowText.java16.13
//计算利率 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.control.TextArea; import javafx.scene.control.ScrollPane; import javafx.scene.control.Button; import javafx.scene.layout.HBox; import javafx.scene.layout.BorderPane; import javafx.geometry.Pos; public class CalculatingInterestRate extends Application { private TextField tfLoanNum = new TextField(); private TextField tfNumYear = new TextField(); private TextArea ta = new TextArea(); @Override public void start(Stage primaryStage) { //设置数据获取面板 tfLoanNum.setPrefColumnCount(10); tfLoanNum.setAlignment(Pos.BOTTOM_RIGHT); tfNumYear.setPrefColumnCount(5); tfNumYear.setAlignment(Pos.BOTTOM_RIGHT); Button btShow =new Button("Show Table"); HBox hbForInf = new HBox(10); hbForInf.setAlignment(Pos.BOTTOM_RIGHT); hbForInf.getChildren().addAll(new Label("Loan Amount"), tfLoanNum, new Label("Number Of Years"), tfNumYear, btShow); ta.setText(String.format("%-20s%-20s%-20s", "Interest Rate", "Monthly Payment", "Total Payment")); btShow.setOnAction(e -> { setTextAreaInf(); }); //为文本域加滚动条 ScrollPane sp = new ScrollPane(ta); //排版 BorderPane pane = new BorderPane(); pane.setTop(hbForInf); pane.setCenter(sp); Scene scene = new Scene(pane); primaryStage.setTitle("CalculatingInterestRate"); primaryStage.setScene(scene); primaryStage.show(); } private void setTextAreaInf() { if (!tfLoanNum.getText().equals("") && !tfNumYear.getText().equals("")) { double loan = Double.parseDouble(tfLoanNum.getText()); double year = Double.parseDouble(tfNumYear.getText()); double monthlyPay = 0.0; double totalPay = 0.0; for (double i = 0.05; i <= 0.08; i += 0.00125) { monthlyPay = ((loan * (i / 12)) / (1 - (1 / Math.pow((1 + i / 12), year * 12)))); totalPay = monthlyPay * year * 12; String inf = String.format("%-20.3f %-20.3f %-20.3f", (i * 100), monthlyPay, totalPay); ta.setText(ta.getText() + "\n" + inf); } } } }16.14
//使用组合框设置文字类型 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.ComboBox; import javafx.scene.text.Font; import javafx.scene.text.Text; import javafx.scene.layout.HBox; import javafx.scene.layout.BorderPane; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Pos; import java.util.List; public class ControlTextFontSize extends Application { @Override public void start(Stage primaryStage) { Text text = new Text(200, 200, "Java is fun!"); //字体类型组合框 ComboBox<String> cboFont = new ComboBox<>(); cboFont.setStyle("-fx-color: red"); cboFont.setPrefWidth(100); //List和ArrayList很相像,返回字体类型 List<String> list = Font.getFamilies(); int size = list.size(); //System.out.println(size); //121种字体 for (int i = 0; i < size; i++) { cboFont.getItems().add(list.get(i)); } cboFont.setValue(list.get(0)); //字体大小组合框 ComboBox<Integer> cboSize = new ComboBox<>(); cboSize.setStyle("-fx-color: blue"); cboSize.setPrefWidth(100); Integer[] textSize = new Integer[100]; for (int i = 0; i < 100; i++) { textSize[i] = i + 1; } cboSize.getItems().addAll(textSize); cboSize.setValue(20); //排版字体和大小组合框 HBox hbForControl = new HBox(10); hbForControl.setAlignment(Pos.CENTER); hbForControl.getChildren().addAll(cboFont, cboSize); //实现组合框功能 cboFont.setOnAction(e -> { text.setFont(Font.font(cboFont.getValue(), cboSize.getValue())); }); cboSize.setOnAction(e -> { text.setFont(Font.font(cboFont.getValue(), cboSize.getValue())); }); //排版 BorderPane pane = new BorderPane(); pane.setPrefSize(400, 300); pane.setTop(hbForControl); pane.setCenter(text); Scene scene = new Scene(pane); primaryStage.setScene(scene); primaryStage.setTitle("ControlTextFontSize"); primaryStage.show(); } }16.15
//动态的调整标签的graphic和text import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.image.ImageView; import javafx.scene.control.ComboBox; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.geometry.Pos; import javafx.scene.control.ContentDisplay; public class ControlLabes extends Application { @Override public void start(Stage primaryStage) { //创建label的节点 ImageView image = new ImageView("image/grapes.gif"); Label lb = new Label("Grapes", image); //创建复选框contentDisplay String[] direction = {"Top", "Right", "Bottom", "Left"}; ObservableList<String> items = FXCollections.observableArrayList(direction); ComboBox<String> cb = new ComboBox<>(); cb.setValue(direction[3]); cb.getItems().addAll(items); //创建graphicTextGap TextField tfGap = new TextField("20"); tfGap.setAlignment(Pos.BOTTOM_RIGHT); tfGap.setPrefColumnCount(5); //排版控制节点 HBox hbForControl = new HBox(10); hbForControl.setAlignment(Pos.CENTER); hbForControl.getChildren().addAll(new Label("contentDisplay"), cb, new Label("graphicTextGap"), tfGap); //排版 BorderPane pane = new BorderPane(); pane.setPrefSize(400, 300); pane.setTop(hbForControl); pane.setCenter(lb); //实现功能 cb.setOnAction(e -> { String str = cb.getValue(); switch (str) { case "Top": lb.setContentDisplay(ContentDisplay.TOP); break; case "Right": lb.setContentDisplay(ContentDisplay.RIGHT); break; case "Bottom": lb.setContentDisplay(ContentDisplay.BOTTOM); break; case "Left": lb.setContentDisplay(ContentDisplay.LEFT); break; } }); tfGap.setOnAction(e -> { Double gap = Double.parseDouble(tfGap.getText()); lb.setGraphicTextGap(gap); }); Scene scene = new Scene(pane); primaryStage.setTitle("ControlLabes"); primaryStage.setScene(scene); primaryStage.show(); } }16.16
//使用复选框设置列表视图的可选模式 import javafx.application.Application; import javafx.stage.Stage; import javafx.scene.Scene; import javafx.scene.control.ComboBox; import javafx.collections.ObservableList; import javafx.collections.FXCollections; import javafx.scene.control.ListView; import javafx.scene.control.SelectionMode; import javafx.scene.control.Label; import javafx.scene.layout.VBox; import javafx.scene.layout.HBox; import javafx.geometry.Pos; public class ControlListViewSelectionMode_UseLabels extends Application { @Override public void start(Stage primaryStage) { //控制视图列表的显示模式的组合框 Label[] modes = {new Label("SINGLE"), new Label("MULTIPLE")}; ObservableList<Label> items = FXCollections.observableArrayList(modes); ComboBox<Label> cbMode = new ComboBox<>(); cbMode.setValue(modes[0]); cbMode.getItems().addAll(items); //视图列表内容 Label[] country = {new Label("Canada"), new Label("China"), new Label("Denmark"), new Label("France"), new Label("Germay"), new Label("India"), new Label("Norway"), new Label("Untied Kingdom"), new Label("Untied States of Amercia")}; ObservableList<Label> itemsCountry = FXCollections.observableArrayList(country); ListView<Label> lvCountry = new ListView<>(); lvCountry.getItems().addAll(itemsCountry); //排版控制部分 HBox hb = new HBox(10); hb.setAlignment(Pos.CENTER); hb.getChildren().addAll(new Label("Chose Selection Mode"), cbMode); VBox pane = new VBox(10); pane.setPrefSize(300, 200); pane.getChildren().addAll(hb, lvCountry); //组合框的功能实现 cbMode.setOnAction(e -> { String str = cbMode.getValue().getText(); if (str.equals("SINGLE")) { lvCountry.getSelectionModel().setSelectionMode(SelectionMode.SINGLE); } else if (str.equals("MULTIPLE")) { lvCountry.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE); } }); Scene scene = new Scene(pane); primaryStage.setTitle("ControlListViewSelectionMode_UseLabels"); primaryStage.setScene(scene); primaryStage.show(); } }