This program is similar to example 72, except now the ObservableList is connected to a ListView.
We break example 72 into 9 steps, and click on a button 9 times, and the ListView node updates. Clicking a 10th time will exit the program.
package ex74;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import java.util.Arrays;
import java.util.List;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
public class Ex74 extends Application {
private final String style1 =
"-fx-font-family: Georgia; -fx-font-size: 24;"
+ "-fx-text-fill: purple; -fx-background-color: greenyellow;";
private final String style2 =
"-fx-font-family: Georgia; -fx-font-size: 24;";
ObservableList obsList;
int step = 1;
private Button button;
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
button = new Button("Do step 1");
appendButtonText(1);
button.setPrefSize(200, 200);
button.setStyle(style1);
button.setWrapText(true);
obsList = FXCollections.observableArrayList();
ListView listView = new ListView<>(obsList);
listView.setPrefSize(200, 400);
listView.setStyle(style2);
button.setOnAction( e -> {
doStep(step);
step++;
if (step<10) {
button.setText("Do step " + step);
appendButtonText(step);
}
else button.setText("No more steps. Exit now!");
});
HBox hbox = new HBox(50, button, listView);
hbox.setPadding(new Insets(20));
Scene scene = new Scene(hbox);
primaryStage.setTitle("Example 74. ListView and Observable List");
primaryStage.setScene(scene);
primaryStage.show();
}
private void doStep(int stepNumber) {
switch (stepNumber) {
case 1:
List list = Arrays.asList("-1", "-2");
obsList.addAll(list);
break;
case 2:
obsList.addAll("1","2","3");
break;
case 3:
obsList.add("4");
break;
case 4:
obsList.add(0, "0");
break;
case 5:
obsList.addAll("4", "5");
break;
case 6:
obsList.set(1, "One");
break;
case 7:
obsList.removeAll("3", "4");
break;
case 8:
obsList.remove("1");
break;
case 9:
obsList.clear();
break;
default:
Platform.exit();
}
}
private void appendButtonText(int stepNumber) {
String val;
switch (stepNumber) {
case 1:
val = " : Adding -1 and -2";
break;
case 2:
val = " : Adding 1, 2, 3";
break;
case 3:
val = " : Adding 4";
break;
case 4:
val = " : Adding 0 at location 0";
break;
case 5:
val = " : Adding 4 and 5";
break;
case 6:
val = " : Changing location 1 to One";
break;
case 7:
val = " : Removing 3 and 4";
break;
case 8:
val = " : Removing 1";
break;
case 9:
val = " : Clearing";
break;
default:
val = " : Exit";
}
button.setText(button.getText() + val);
}
}
This is the output after 5 steps and before Step 6 which will put One in location 1 (replacing -1):
No comments:
Post a Comment