set CheckBoxTreeItem to always selected - javafx

I'm using a tree view to navigate faster in my printing view. Before the user Is printing a document he can select or deselect columns. Some of the columns are mandatory so what I want to do is that they are always selected, even when the user is trying to deselect them. This is an example of how it looks like. How can I set the selection for an item to true and keep it like that?
public class TreeItemExample extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Hello World!");
AnchorPane root = new AnchorPane();
TreeView<String> treeView = new TreeView<>();
CheckBoxTreeItem<String> rootItem = new CheckBoxTreeItem<>("Example");
CheckBoxTreeItem<String> mandatoryItem = new CheckBoxTreeItem<>("A");
CheckBoxTreeItem<String> optionalItem = new CheckBoxTreeItem<>("B");
mandatoryItem.setSelected(true);
mandatoryItem.selectedProperty().addListener((observable, oldValue, newValue) -> {
newValue = true;
mandatoryItem.setSelected(true);
});
rootItem.getChildren().addAll(mandatoryItem, optionalItem);
treeView.setRoot(rootItem);
treeView.setCellFactory(CheckBoxTreeCell.<String>forTreeView());
root.getChildren().add(treeView);
primaryStage.setScene(new Scene(root, 300, 250));
primaryStage.show();
}
}

Change mandatoryItem selectedProperty listener to:
mandatoryItem.selectedProperty().addListener((observable, oldValue, newValue) -> {
Platform.runLater(() -> mandatoryItem.setSelected(true));
});

Related

Clearing the scene in javafx

I need a help with JavaFX. I have a program that draws lines with the mouse in the scene. When I press clear button, whole scene needs to be cleared. But only last drawn line is being cleared with this program.
When clear button is pushed, all drawn lines should be cleared. Now, only the last drawn line is being cleared.
public class Test extends Application {
private Line currentLine;
private Group root;
private ColorPicker colorPicker;
private Button clearButton;
private HBox buttons;
private Scene scene;
public void start(Stage primaryStage) {
root = new Group();
colorPicker = new ColorPicker(Color.WHITE);
clearButton = new Button("Clear");
clearButton.setOnAction(this::processActionButton);
buttons = new HBox(colorPicker, clearButton);
buttons.setSpacing(15);
root.getChildren().addAll(buttons);
scene = new Scene(root, 500, 300, Color.BLACK);
scene.setOnMousePressed(this::processMousePress);
scene.setOnMouseDragged(this::processMouseDrag);
primaryStage.setTitle("Color Lines");
primaryStage.setScene(scene);
primaryStage.show();
}
public void processMousePress(MouseEvent event) {
currentLine = new Line(event.getX(), event.getY(), event.getX(),
event.getY());
currentLine.setStroke(colorPicker.getValue());
currentLine.setStrokeWidth(3);
root.getChildren().add(currentLine);
}
public void processMouseDrag(MouseEvent event) {
currentLine.setEndX(event.getX());
currentLine.setEndY(event.getY());
}
public void processActionButton(ActionEvent event) {
root.getChildren().removeAll(currentLine);
}
public static void main(String[] args) {
launch(args);
}
}
You can have a special group for lines only:
Group groupLines = new Group();
...
root.getChildren().add(groupLines);
Add new lines into this group:
public void processMousePress(MouseEvent event) {
...
groupLines.getChildren().add(currentLine);
}
And clean only this group:
groupLines.getChildren().clear();

JavaFX Stage.close() not calling my onCloseRequest() handler

Please refer to the JavaFX SSCCE below. The print statement appears when closing the primary stage from the window's default titlebar "X" button. The print statement does NOT appear when clicking the "Close" button. Why isn't my onCloseHandler being called when I call close() on the stage? Is my expectation somehow unreasonable or is this (yet another) bug in JavaFX? Thanks!
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Button closeButton = new Button("Close");
closeButton.setOnAction(e -> {
primaryStage.close();
});
primaryStage.setOnCloseRequest(e -> {
System.out.println("onCloseRequest handler called!");
});
StackPane rootPane = new StackPane();
rootPane.getChildren().add(closeButton);
primaryStage.setScene(new Scene(rootPane, 300, 250));
primaryStage.show();
}
}
As described by the Javadoc, this is only fired on external requests:
Called when there is an external request to close this Window.
Maybe setOnHidden would work for you, it is called in both cases.
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
Button closeButton = new Button("Close");
closeButton.setOnAction(e -> {
primaryStage.close();
});
primaryStage.setOnHidden(e -> {
System.out.println("stage hidden");
});
StackPane rootPane = new StackPane();
rootPane.getChildren().add(closeButton);
primaryStage.setScene(new Scene(rootPane, 300, 250));
primaryStage.show();
}
}

javafx putting textarea value into a hashmap

I would like to make a small java fx app that has just textarea and one button on a stage and that when you type some strings in textarea and press submit it shows on the stage small table with results how many each Word had occurrences.
so my questions is: does map is the best solution for finding the occurrences even though I do not know what will be the key for finding occurrences and how to connect string from text area, to map.
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Word counting");
TextArea txt=new TextArea();
txt.setMaxSize(450, 200);
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
primaryStage.hide();
ShowResults.drugiProzor();
}
});
BorderPane root = new BorderPane();
root.setTop(txt);
HBox hbox=new HBox();
hbox.setPadding(new Insets(20,20,100,180));
hbox.getChildren().add(btn);
root.setBottom(hbox);
Scene scene = new Scene(root, 450, 300);
primaryStage.setTitle("Word counting!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
and the second class is again gui class with table view
public class ShowResults {
static Stage secondaryStage;
public static void drugiProzor() {
secondaryStage=new Stage();
TableView table=new TableView();
TableColumn column1=new TableColumn("Word");
column1.setMinWidth(200);
TableColumn column2=new TableColumn("Number of occurencies");
column2.setMinWidth(200);
table.getColumns().addAll(column1,column2);
StackPane pane=new StackPane();
pane.getChildren().add(table);
Scene scene = new Scene(pane, 450, 300);
secondaryStage.setScene(scene);
secondaryStage.setTitle("Counting words");
secondaryStage.show();
}
}
and third class shoyld be the class where the magic happends something like this:
public class Logic {
public void logic()
}
}
You can just do something like
public Map<String, Long> countWordOccurences(String text) {
return Pattern.compile("\\s+") // regular expression matching 1 or more whitespace
.splitAsStream(text) // split at regular expression and stream words between
// group by the words themselves and count each group:
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
}
Check the Javadocs to see what each step is doing: Pattern, Collectors.groupingBy(), Function, etc.
If you want to count in a case-insensitive way, you can replace Function.identity() with String::toLowerCase
.collect(Collectors.groupingBy(String::toLowerCase, Collectors.counting()));
and if you want to ignore punctuation, you can add
map(s -> s.replaceAll("[^a-zA-Z]",""))
to the pipeline.

how to close other tabs except the selected tab

I want to implement TabPane with ContextMenu to close other tabs except the selected tab
public class MainApp extends Application
{
#Override
public void start(Stage primaryStage)
{
primaryStage.setTitle("Tabs");
Group root = new Group();
Scene scene = new Scene(root, 400, 250, Color.WHITE);
final TabPane tabPane = new TabPane();
BorderPane borderPane = new BorderPane();
for (int i = 0; i < 5; i++)
{
Tab tab = new Tab();
tab.setText("Tab" + i);
HBox hbox = new HBox();
hbox.getChildren().add(new Label("Tab" + i));
hbox.setAlignment(Pos.CENTER);
tab.setContent(hbox);
tabPane.getTabs().add(tab);
ContextMenu contextMenu = new ContextMenu();
MenuItem close = new MenuItem();
MenuItem closeOthers = new MenuItem();
MenuItem closeAll = new MenuItem();
close.setText("Close");
closeOthers.setText("Close Others");
closeAll.setText("Close All");
contextMenu.getItems().addAll(close, closeOthers, closeAll);
tab.setContextMenu(contextMenu);
final ObservableList<Tab> tablist = tabPane.getTabs();
close.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
tabPane.getTabs().remove(tabPane.getSelectionModel().getSelectedItem());
}
});
closeOthers.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
tabPane.getTabs().removeAll();
}
});
closeAll.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
tabPane.getTabs().removeAll(tablist);
}
});
}
// bind to take available space
borderPane.prefHeightProperty().bind(scene.heightProperty());
borderPane.prefWidthProperty().bind(scene.widthProperty());
borderPane.setCenter(tabPane);
root.getChildren().add(borderPane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
But the code is not working. Can you help me to implement this solution.
Is there any better approach to implement this?
This is pretty simple. Just iterate through all Tab-Objects in the tablist and mark the ones which should be deleted. After the iteration remove the marked Tab-Objects.
closeOthers.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
// ArrayList of Tab-Objects in which we store Tabs which should be deleted..
ArrayList<Tab> markedTabs = new ArrayList<>();
// Iterate through all Tabs in tablist
for (Tab tab : tablist) {
// Is the tab the current active tab? if not, add it to the markedTabs-ArrayList
if (tab != tabPane.getSelectionModel().getSelectedItem())
markedTabs.add(tab);
}
// Remove them from the tabPane..
tabPane.getTabs().removeAll(markedTabs);
}
});

Javafx : How I can add unique Elements into Listview (i.e Duplicate Element Get Skipped)

I am new to use javafx i want to use list with unique element in javafx how i can manage it . Display the Content of List view should be unique duplicates value get skipped.
thank you
static ObservableList<String> items = FXCollections.observableArrayList();
static ObservableList<String> bamitems = FXCollections
.observableArrayList();
static ListView<String> list;
static ListView<String> listforbam;
public static void test() throws Exception {
HBox root = new HBox();
VBox yesaccordion = new VBox();
Accordion acc = new Accordion();
acc.getPanes().addAll(createPanes());
yesaccordion.getChildren().add(acc);
root.getChildren().addAll(yesaccordion);
jfxpanel.setScene(new Scene(root, 200, 100));
panel.add(jfxpanel);
items.addAll(LoadVCFFileToTrack.destitemlist);
bamitems.addAll(LoadVCFFileToTrack.destitemBamlist);
if (LoadVCFFileToTrack.destitemBamlist.size() > 0) {
listforbam = new ListView<String>();
listforbam.setItems(bamitems);
}
if (LoadVCFFileToTrack.destitemlist.size() > 0) {
list = new ListView<String>();
list.setItems(items);
}
Use a Set or better an ObservableSet to store the items you want to display in the ListView.
To add the set to the list view you can use FXCollections.observableArrayList(Collection col) method. It will convert the ObservableSet to ObservableArrayList.
listView.setItems(FXCollections.observableArrayList(observableSet));
Complete example
public class Main extends Application {
#Override
public void start(Stage stage) {
ObservableSet<String> observableSet = FXCollections.observableSet();
//Item1 is repeated twice
observableSet.addAll(Arrays.asList("Item1","Item2","Item3", "Item1"));
ListView<String> listView = new ListView<>();
listView.setItems(FXCollections.observableArrayList(observableSet));
stage.setScene(new Scene(listView, 200, 200));
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}

Resources