package collection;
import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
public class Exercise20_02 extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
TextField number = new TextField();
HBox topHBox = new HBox(10, new Label("Enter a number:"), number); //顶部
topHBox.setAlignment(Pos.CENTER);
TextArea textArea = new TextArea(); //中部
textArea.setPrefRowCount(6);
textArea.setPrefColumnCount(31);
textArea.setEditable(false);
Button sort = new Button("Sort");
Button shuffle = new Button("Shuffle");
Button reverse = new Button("Reverse");
HBox bottomHBox = new HBox(10, sort, shuffle, reverse); //底部
bottomHBox.setAlignment(Pos.CENTER);
LinkedList<Integer> linkedList = new LinkedList<>();
number.setOnAction(event -> { //按钮注册动作事件
try {
add(linkedList, Integer.parseInt(number.getText()));
addText(linkedList, textArea);
number.setText("");
} catch (NumberFormatException ex) {
}
});
sort.setOnAction(event -> {
Collections.sort(linkedList);
addText(linkedList, textArea);
});
shuffle.setOnAction(event -> {
Collections.shuffle(linkedList);
addText(linkedList, textArea);
});
reverse.setOnAction(event -> {
Collections.reverse(linkedList);
addText(linkedList, textArea);
});
BorderPane pane = new BorderPane(new ScrollPane(textArea)); //总面板
pane.setTop(topHBox);
pane.setBottom(bottomHBox);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.setTitle("Exercise20_02");
primaryStage.show();
}
/** 不重复的值添加进链表 */
private void add(LinkedList<Integer> linkedList, int value) {
boolean isTheSame = false;
for (Integer i : linkedList) //遍历链表
if (i.equals(value)) //如果值重复,变量设置为true
isTheSame = true;
if (!isTheSame) //值不重复时添加进链表
linkedList.addLast(value);
}
/** 添加链表数据到文本区域 */
private void addText(LinkedList<Integer> linkedList, TextArea textArea) {
textArea.clear(); //清除原有文本区域数据
Iterator<Integer> iterator = linkedList.iterator(); //返回链表迭代器
while (iterator.hasNext()) //遍历迭代器,追加数据
textArea.appendText(iterator.next() + " ");
}
}