Code is not working properly when row is clicked - javafx-2

Can you help me to fix this code. It's not working working properly as I expected.
package javafxapplication2;
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Callback;
class Person {
private StringProperty aliasName;
private StringProperty newPanelName;
private StringProperty newPanelDescription;
private ObservableList<Person> panels = FXCollections.observableArrayList();
public final void setAliasName(String value) {
aliasNameProperty().set(value);
}
public final String getAliasName() {
return aliasNameProperty().get();
}
public StringProperty aliasNameProperty() {
if (aliasName == null) {
aliasName = new SimpleStringProperty();
}
return aliasName;
}
public final void setNewPanelName(String value) {
newPanelNameProperty().set(value);
}
public final String getNewPanelName() {
return newPanelNameProperty().get();
}
public StringProperty newPanelNameProperty() {
if (newPanelName == null) {
newPanelName = new SimpleStringProperty();
}
return newPanelName;
}
public final void setNewPanelDescription(String value) {
newPanelDescriptionProperty().set(value);
}
public final String getNewPanelDescription() {
return newPanelDescriptionProperty().get();
}
public StringProperty newPanelDescriptionProperty() {
if (newPanelDescription == null) {
newPanelDescription = new SimpleStringProperty();
}
return newPanelDescription;
}
public ObservableList<Person> panelsProperty() {
return panels;
}
public Person(String alias, String newPanelName, String newPanelDescription) {
setAliasName(alias);
setNewPanelName(newPanelName);
setNewPanelDescription(newPanelDescription);
}
}
public class JavaFXApplication2 extends Application {
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(final Stage primaryStage) {
primaryStage.setTitle("test");
Group root = new Group();
Scene scene = new Scene(root, 500, 250, Color.WHITE);
// create a grid pane
GridPane gridpane = new GridPane();
gridpane.setPadding(new Insets(5));
gridpane.setHgap(10);
gridpane.setVgap(10);
ObservableList<Person> leaders = FXCollections.observableArrayList();
leaders.add(new Person("test 1", "test 11", "test 111"));
leaders.add(new Person("test 2", "test 22", "test 222"));
leaders.add(new Person("test 3", "test 33", "test 333"));
leaders.add(new Person("test 4", "test 44", "test 444"));
final ListView<Person> leaderListView = new ListView<>(leaders);
leaderListView.setPrefWidth(450);
leaderListView.setPrefHeight(150);
//
leaderListView.setCellFactory(new Callback<ListView<Person>, ListCell<Person>>() {
#Override
public ListCell<Person> call(ListView<Person> param) {
final Label leadLbl = new Label();
final Tooltip tooltip = new Tooltip();
final ListCell<Person> cell = new ListCell<Person>() {
#Override
public void updateItem(Person item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
leadLbl.setText(item.getAliasName());
setText(item.getNewPanelName());// + " " + item.getNewPanelDescription());
tooltip.setText(item.getAliasName());
setTooltip(tooltip);
}
}
}; // ListCell
return cell;
}
}); // setCellFactory
// Double click
leaderListView.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getButton().equals(MouseButton.PRIMARY)) {
if (mouseEvent.getClickCount() == 2) {
Person item = leaderListView.getSelectionModel().getSelectedItem();
if (item != null) {
StackPane pane = new StackPane();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
pane.getChildren().add(new TextField(item.getAliasName()));
stage.show();
}
}
}
}
});
gridpane.add(leaderListView, 0, 1);
// Buttons
// Button "Open"
Button btnYes = new Button("Open");
btnYes.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
leaderListView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Person>() {
#Override
public void changed(ObservableValue<? extends Person> observable, Person oldValue, Person newValue) {
Person item = leaderListView.getSelectionModel().getSelectedItem();
if (item != null) {
StackPane pane = new StackPane();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
pane.getChildren().add(new TextField(item.getAliasName()));
stage.show();
}
System.out.println("selection changed");
}
});
}
});
// Button "Cancel"
Button btnNo = new Button("Cancel");
btnNo.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
primaryStage.close();
}
});
HBox hbox = new HBox();
hbox.setSpacing(10);
hbox.setAlignment(Pos.CENTER);
hbox.getChildren().add(btnYes);
hbox.getChildren().add(btnNo);
gridpane.add(hbox, 0, 2);
root.getChildren().add(gridpane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
I want to select one row and then to open a new window when I click the button Select to open a new window. Can you help me to fix the code?

Replace the btnYes.setOnAction with the following :
btnYes.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Person item = leaderListView.getSelectionModel().getSelectedItem();
if (item != null) {
StackPane pane = new StackPane();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
pane.getChildren().add(new TextField(item.getAliasName()));
stage.show();
}
}
});

It should be this the action of the btnYes:
btnYes.setOnAction(new EventHandler<ActionEvent>()
{
#Override
public void handle(ActionEvent event)
{
Person item = leaderListView.getSelectionModel().getSelectedItem();
if (item != null) {
StackPane pane = new StackPane();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
pane.getChildren().add(new TextField(item.getAliasName()));
stage.show();
}
}
});
(there might be an axtra braket, just edited online.)
Also, this is exactly the same code as in the list doubleclick event, might want to put it in a diferent method, so that you dont repeat code:
public void openNewWindow(){
Person item = leaderListView.getSelectionModel().getSelectedItem();
if (item != null) {
StackPane pane = new StackPane();
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
pane.getChildren().add(new TextField(item.getAliasName()));
stage.show();
}

Related

Remove LabelBuilder TextAreaBuilder StackPaneBuilder VBoxBuilder

I want to update the code of this example:
http://www.java2s.com/Code/Java/JavaFX/StackPanebasedwizard.htm
package javafxwizard;
import javafx.application.Application;
import javafx.stage.Stage;
import java.util.Stack;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.LabelBuilder;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextAreaBuilder;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.StackPaneBuilder;
import javafx.scene.layout.VBox;
import javafx.scene.layout.VBoxBuilder;
public class JavaFXWizard extends Application {
public static void main(String[] args) throws Exception {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(new SurveyWizard(stage), 400, 250));
stage.show();
}
}
class Wizard extends StackPane {
private static final int UNDEFINED = -1;
private ObservableList<WizardPage> pages = FXCollections
.observableArrayList();
private Stack<Integer> history = new Stack<>();
private int curPageIdx = UNDEFINED;
Wizard(WizardPage... nodes) {
pages.addAll(nodes);
navTo(0);
setStyle("-fx-padding: 10; -fx-background-color: cornsilk;");
}
void nextPage() {
if (hasNextPage()) {
navTo(curPageIdx + 1);
}
}
void priorPage() {
if (hasPriorPage()) {
navTo(history.pop(), false);
}
}
boolean hasNextPage() {
return (curPageIdx < pages.size() - 1);
}
boolean hasPriorPage() {
return !history.isEmpty();
}
void navTo(int nextPageIdx, boolean pushHistory) {
if (nextPageIdx < 0 || nextPageIdx >= pages.size()) {
return;
}
if (curPageIdx != UNDEFINED) {
if (pushHistory) {
history.push(curPageIdx);
}
}
WizardPage nextPage = pages.get(nextPageIdx);
curPageIdx = nextPageIdx;
getChildren().clear();
getChildren().add(nextPage);
nextPage.manageButtons();
}
void navTo(int nextPageIdx) {
navTo(nextPageIdx, true);
}
void navTo(String id) {
Node page = lookup("#" + id);
if (page != null) {
int nextPageIdx = pages.indexOf(page);
if (nextPageIdx != UNDEFINED) {
navTo(nextPageIdx);
}
}
}
public void finish() {
}
public void cancel() {
}
}
/**
* basic wizard page class
*/
abstract class WizardPage extends VBox {
Button priorButton = new Button("_Previous");
Button nextButton = new Button("N_ext");
Button cancelButton = new Button("Cancel");
Button finishButton = new Button("_Finish");
WizardPage(String title) {
getChildren().add(
LabelBuilder.create().text(title)
.style("-fx-font-weight: bold; -fx-padding: 0 0 5 0;").build());
setId(title);
setSpacing(5);
setStyle("-fx-padding:10; -fx-background-color: honeydew; -fx-border-color: derive(honeydew, -30%); -fx-border-width: 3;");
Region spring = new Region();
VBox.setVgrow(spring, Priority.ALWAYS);
getChildren().addAll(getContent(), spring, getButtons());
priorButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
priorPage();
}
});
nextButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
nextPage();
}
});
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
getWizard().cancel();
}
});
finishButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
getWizard().finish();
}
});
}
HBox getButtons() {
Region spring = new Region();
HBox.setHgrow(spring, Priority.ALWAYS);
HBox buttonBar = new HBox(5);
cancelButton.setCancelButton(true);
finishButton.setDefaultButton(true);
buttonBar.getChildren().addAll(spring, priorButton, nextButton,
cancelButton, finishButton);
return buttonBar;
}
abstract Parent getContent();
boolean hasNextPage() {
return getWizard().hasNextPage();
}
boolean hasPriorPage() {
return getWizard().hasPriorPage();
}
void nextPage() {
getWizard().nextPage();
}
void priorPage() {
getWizard().priorPage();
}
void navTo(String id) {
getWizard().navTo(id);
}
Wizard getWizard() {
return (Wizard) getParent();
}
public void manageButtons() {
if (!hasPriorPage()) {
priorButton.setDisable(true);
}
if (!hasNextPage()) {
nextButton.setDisable(true);
}
}
}
/**
* This class shows a satisfaction survey
*/
class SurveyWizard extends Wizard {
Stage owner;
public SurveyWizard(Stage owner) {
super(new ComplaintsPage(), new MoreInformationPage(), new ThanksPage());
this.owner = owner;
}
#Override
public void finish() {
System.out.println("Had complaint? "
+ SurveyData.instance.hasComplaints.get());
if (SurveyData.instance.hasComplaints.get()) {
System.out.println("Complaints: "
+ (SurveyData.instance.complaints.get().isEmpty() ? "No Details"
: "\n" + SurveyData.instance.complaints.get()));
}
owner.close();
}
#Override
public void cancel() {
System.out.println("Cancelled");
owner.close();
}
}
/**
* Simple placeholder class for the customer entered survey response.
*/
class SurveyData {
BooleanProperty hasComplaints = new SimpleBooleanProperty();
StringProperty complaints = new SimpleStringProperty();
static SurveyData instance = new SurveyData();
}
/**
* This class determines if the user has complaints. If not, it jumps to the
* last page of the wizard.
*/
class ComplaintsPage extends WizardPage {
private RadioButton yes;
private RadioButton no;
private ToggleGroup options = new ToggleGroup();
public ComplaintsPage() {
super("Complaints");
nextButton.setDisable(true);
finishButton.setDisable(true);
yes.setToggleGroup(options);
no.setToggleGroup(options);
options.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
#Override
public void changed(ObservableValue<? extends Toggle> observableValue,
Toggle oldToggle, Toggle newToggle) {
nextButton.setDisable(false);
finishButton.setDisable(false);
}
});
}
#Override
Parent getContent() {
yes = new RadioButton("Yes");
no = new RadioButton("No");
SurveyData.instance.hasComplaints.bind(yes.selectedProperty());
return VBoxBuilder.create().spacing(5)
.children(new Label("Do you have complaints?"), yes, no).build();
}
#Override
void nextPage() {
// If they have complaints, go to the normal next page
if (options.getSelectedToggle().equals(yes)) {
super.nextPage();
} else {
// No complaints? Short-circuit the rest of the pages
navTo("Thanks");
}
}
}
/**
* This page gathers more information about the complaint
*/
class MoreInformationPage extends WizardPage {
public MoreInformationPage() {
super("More Info");
}
#Override
Parent getContent() {
TextArea textArea = TextAreaBuilder.create().wrapText(true).build();
nextButton.setDisable(true);
textArea.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(ObservableValue<? extends String> observableValue,
String oldValue, String newValue) {
nextButton.setDisable(newValue.isEmpty());
}
});
SurveyData.instance.complaints.bind(textArea.textProperty());
return VBoxBuilder.create().spacing(5)
.children(new Label("Please enter your complaints."), textArea).build();
}
}
/**
* This page thanks the user for taking the survey
*/
class ThanksPage extends WizardPage {
public ThanksPage() {
super("Thanks");
}
#Override
Parent getContent() {
StackPane stack = StackPaneBuilder.create().children(new Label("Thanks!"))
.build();
VBox.setVgrow(stack, Priority.ALWAYS);
return stack;
}
}
Can you help me to update the code? In Java 8 LabelBuilder TextAreaBuilder StackPaneBuilder VBoxBuilder are obsolete code?
Can you help me to simplify the code and update it for Java 8?
Here is the same code, but without the builders... Buts its the same Logic:
import javafx.application.Application;
import javafx.stage.Stage;
import java.util.Stack;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextArea;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
public class JavaFXWizard extends Application {
public static void main(String[] args) throws Exception {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
stage.setScene(new Scene(new SurveyWizard(stage), 400, 250));
stage.show();
}
}
class Wizard extends StackPane {
private static final int UNDEFINED = -1;
private ObservableList<WizardPage> pages = FXCollections
.observableArrayList();
private Stack<Integer> history = new Stack<>();
private int curPageIdx = UNDEFINED;
Wizard(WizardPage... nodes) {
pages.addAll(nodes);
navTo(0);
setStyle("-fx-padding: 10; -fx-background-color: cornsilk;");
}
void nextPage() {
if (hasNextPage()) {
navTo(curPageIdx + 1);
}
}
void priorPage() {
if (hasPriorPage()) {
navTo(history.pop(), false);
}
}
boolean hasNextPage() {
return (curPageIdx < pages.size() - 1);
}
boolean hasPriorPage() {
return !history.isEmpty();
}
void navTo(int nextPageIdx, boolean pushHistory) {
if (nextPageIdx < 0 || nextPageIdx >= pages.size()) {
return;
}
if (curPageIdx != UNDEFINED) {
if (pushHistory) {
history.push(curPageIdx);
}
}
WizardPage nextPage = pages.get(nextPageIdx);
curPageIdx = nextPageIdx;
getChildren().clear();
getChildren().add(nextPage);
nextPage.manageButtons();
}
void navTo(int nextPageIdx) {
navTo(nextPageIdx, true);
}
void navTo(String id) {
Node page = lookup("#" + id);
if (page != null) {
int nextPageIdx = pages.indexOf(page);
if (nextPageIdx != UNDEFINED) {
navTo(nextPageIdx);
}
}
}
public void finish() {
}
public void cancel() {
}
}
/**
* basic wizard page class
*/
abstract class WizardPage extends VBox {
Button priorButton = new Button("_Previous");
Button nextButton = new Button("N_ext");
Button cancelButton = new Button("Cancel");
Button finishButton = new Button("_Finish");
WizardPage(String title) {
Label label = new Label(title);
label.setStyle("-fx-font-weight: bold; -fx-padding: 0 0 5 0;");
getChildren().add(label);
setId(title);
setSpacing(5);
setStyle("-fx-padding:10; -fx-background-color: honeydew; -fx-border-color: derive(honeydew, -30%); -fx-border-width: 3;");
Region spring = new Region();
VBox.setVgrow(spring, Priority.ALWAYS);
getChildren().addAll(getContent(), spring, getButtons());
priorButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
priorPage();
}
});
nextButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
nextPage();
}
});
cancelButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
getWizard().cancel();
}
});
finishButton.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent actionEvent) {
getWizard().finish();
}
});
}
HBox getButtons() {
Region spring = new Region();
HBox.setHgrow(spring, Priority.ALWAYS);
HBox buttonBar = new HBox(5);
cancelButton.setCancelButton(true);
finishButton.setDefaultButton(true);
buttonBar.getChildren().addAll(spring, priorButton, nextButton,
cancelButton, finishButton);
return buttonBar;
}
abstract Parent getContent();
boolean hasNextPage() {
return getWizard().hasNextPage();
}
boolean hasPriorPage() {
return getWizard().hasPriorPage();
}
void nextPage() {
getWizard().nextPage();
}
void priorPage() {
getWizard().priorPage();
}
void navTo(String id) {
getWizard().navTo(id);
}
Wizard getWizard() {
return (Wizard) getParent();
}
public void manageButtons() {
if (!hasPriorPage()) {
priorButton.setDisable(true);
}
if (!hasNextPage()) {
nextButton.setDisable(true);
}
}
}
/**
* This class shows a satisfaction survey
*/
class SurveyWizard extends Wizard {
Stage owner;
public SurveyWizard(Stage owner) {
super(new ComplaintsPage(), new MoreInformationPage(), new ThanksPage());
this.owner = owner;
}
#Override
public void finish() {
System.out.println("Had complaint? "
+ SurveyData.instance.hasComplaints.get());
if (SurveyData.instance.hasComplaints.get()) {
System.out
.println("Complaints: "
+ (SurveyData.instance.complaints.get().isEmpty() ? "No Details"
: "\n"
+ SurveyData.instance.complaints
.get()));
}
owner.close();
}
#Override
public void cancel() {
System.out.println("Cancelled");
owner.close();
}
}
/**
* Simple placeholder class for the customer entered survey response.
*/
class SurveyData {
BooleanProperty hasComplaints = new SimpleBooleanProperty();
StringProperty complaints = new SimpleStringProperty();
static SurveyData instance = new SurveyData();
}
/**
* This class determines if the user has complaints. If not, it jumps to the
* last page of the wizard.
*/
class ComplaintsPage extends WizardPage {
private RadioButton yes;
private RadioButton no;
private ToggleGroup options = new ToggleGroup();
public ComplaintsPage() {
super("Complaints");
nextButton.setDisable(true);
finishButton.setDisable(true);
yes.setToggleGroup(options);
no.setToggleGroup(options);
options.selectedToggleProperty().addListener(
new ChangeListener<Toggle>() {
#Override
public void changed(
ObservableValue<? extends Toggle> observableValue,
Toggle oldToggle, Toggle newToggle) {
nextButton.setDisable(false);
finishButton.setDisable(false);
}
});
}
#Override
Parent getContent() {
yes = new RadioButton("Yes");
no = new RadioButton("No");
SurveyData.instance.hasComplaints.bind(yes.selectedProperty());
VBox vBox = new VBox();
vBox.setSpacing(5);
vBox.getChildren()
.addAll(new Label("Do you have complaints?"), yes, no);
return vBox;
}
#Override
void nextPage() {
// If they have complaints, go to the normal next page
if (options.getSelectedToggle().equals(yes)) {
super.nextPage();
} else {
// No complaints? Short-circuit the rest of the pages
navTo("Thanks");
}
}
}
/**
* This page gathers more information about the complaint
*/
class MoreInformationPage extends WizardPage {
public MoreInformationPage() {
super("More Info");
}
#Override
Parent getContent() {
TextArea textArea = new TextArea();
textArea.setWrapText(true);
nextButton.setDisable(true);
textArea.textProperty().addListener(new ChangeListener<String>() {
#Override
public void changed(
ObservableValue<? extends String> observableValue,
String oldValue, String newValue) {
nextButton.setDisable(newValue.isEmpty());
}
});
SurveyData.instance.complaints.bind(textArea.textProperty());
VBox vBox = new VBox();
vBox.setSpacing(5);
vBox.getChildren().addAll(new Label("Please enter your complaints."),
textArea);
return vBox;
}
}
/**
* This page thanks the user for taking the survey
*/
class ThanksPage extends WizardPage {
public ThanksPage() {
super("Thanks");
}
#Override
Parent getContent() {
StackPane stack = new StackPane();
stack.getChildren().add(new Label("Thanks!"));
VBox.setVgrow(stack, Priority.ALWAYS);
return stack;
}
}

JavaFX2: MODAL capability to a context menu

Is there a way to add MODAL capability to a context menu?
My code is below:
package snippet;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.ColorPicker;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.Label;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class ContextMenuSample extends Application
{
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(Stage stage)
{
stage.setTitle("ContextMenuSample");
Scene scene = new Scene(new Group(), 450, 250);
Label toLabel = new Label("To: ");
TextField notification = new TextField();
final ContextMenu contextMenu = new ContextMenu();
contextMenu.setAutoHide(false);
contextMenu.setOnShowing(new EventHandler<WindowEvent>()
{
public void handle(WindowEvent e)
{
System.out.println("showing the context menu");
}
});
contextMenu.setOnShown(new EventHandler<WindowEvent>()
{
public void handle(WindowEvent e)
{
System.out.println("context menu has been shown");
}
});
MenuItem closeItem = new MenuItem("Close");
closeItem.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent e)
{
contextMenu.hide();
}
});
MenuItem colorItem = new MenuItem("Choose", new ColorPicker());
colorItem.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent e)
{
System.out.println("Preferences");
}
});
GridPane contextGridPane = new GridPane();
Pane pane = new Pane();
pane.getChildren().add(contextGridPane);
contextMenu.getItems().addAll(colorItem, deleteItem// , subsystem1,
// radioItem
);
toLabel.setContextMenu(contextMenu);
GridPane grid = new GridPane();
grid.setVgap(4);
grid.setHgap(10);
grid.setPadding(new Insets(5, 5, 5, 5));
grid.add(toLabel, 0, 0);
grid.add(notification, 1, 0);
grid.add(new ColorPicker(), 2, 0);
Group root = (Group) scene.getRoot();
root.getChildren().add(grid);
stage.setScene(scene);
stage.show();
}
}
When the user clicks on the label "To", a context menu appears. I wish to have modal capability for this context menu such that the user is not able to do anything else on the application unless some operation is performed on the context menu. Also, when the context menu is active, the user should not be able to click anywhere else on the application.
Regards,
The easiest solution would be to call another Stage and set its modality with initModality before you show the stage. You probably want to use Modality.APPLICATION_MODEL as far as I understood you.
Here is a small example derived from yours (btw your code was not even runnable, it had errors)
public class ContextMenuSample extends Application
{
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(final Stage stageOne)
{
final Stage stageTwo = new Stage();
stageTwo.initModality(Modality.APPLICATION_MODAL);
final Pane layoutOne = new HBox(10);
Pane layoutTwo = new HBox(10);
Label labelOne = new Label("click");
Label labelTwo = new Label("other click");
labelOne.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
stageTwo.show();
}
});
labelTwo.setOnMouseClicked(new EventHandler<MouseEvent>() {
#Override
public void handle(MouseEvent event) {
stageTwo.close();
}
});
Scene sceneOne = new Scene(layoutOne);
Scene sceneTwo = new Scene(layoutTwo);
layoutOne.getChildren().add(labelOne);
layoutTwo.getChildren().add(labelTwo);
stageOne.setScene(sceneOne);
stageTwo.setScene(sceneTwo);
stageOne.show();
}
}

JavaFx 2 - Display color in ComboBox

Following the Oracle's example for a ListView, I have been able to get a ComboBox color rendering a list of color
My problem is that once a color is selected, ComboBox display the string name while I would like to display the color itself, with or without the color name aside.
How to change this code in order to get the selected color displayed?
Thanks all.
import javafx.application.Application;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.ComboBox;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.stage.Stage;
import javafx.util.Callback;
public class ProvaComboRendering extends Application {
#Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
ComboBox<String> cb = new ComboBox<String>();
cb.setPrefSize(150, 20);
root.getChildren().add(cb);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
ObservableList<String> data = FXCollections.observableArrayList(
"chocolate", "salmon", "gold", "coral", "darkorchid",
"darkgoldenrod", "lightsalmon", "black", "rosybrown", "blue",
"blueviolet", "brown");
cb.setItems(data);
cb.setCellFactory(new Callback<ListView<String>, ListCell<String>>(){
#Override
public ListCell<String> call(ListView<String> list){
return new ColorRectCell();
}
});
}
static class ColorRectCell extends ListCell<String>{
#Override
public void updateItem(String item, boolean empty){
super.updateItem(item, empty);
Rectangle rect = new Rectangle(120,18);
if(item != null){
rect.setFill(Color.web(item));
setGraphic(rect);
}
}
}
public static void main(String[] args) {
launch(args);
}
}
Edit: Is it possibile to show a tooltip displaing the name of the color while the mouse pointer is over one of the color list?
Use ComboBox's button cell property. You can use the same cellfactory:
#Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
ComboBox<String> cb = new ComboBox<String>();
cb.setPrefSize(150, 20);
root.getChildren().add(cb);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
ObservableList<String> data = FXCollections.observableArrayList(
"chocolate", "salmon", "gold", "coral", "darkorchid",
"darkgoldenrod", "lightsalmon", "black", "rosybrown", "blue",
"blueviolet", "brown");
cb.setItems(data);
Callback<ListView<String>, ListCell<String>> factory = new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> list) {
return new ColorRectCell();
}
};
cb.setCellFactory(factory);
cb.setButtonCell(factory.call(null));
}
or define a new cell factory for button cell, like below which adds a tooltipablity :
#Override
public void start(Stage primaryStage) {
StackPane root = new StackPane();
ComboBox<String> cb = new ComboBox<String>();
cb.setPrefSize(150, 20);
root.getChildren().add(cb);
Scene scene = new Scene(root, 300, 250);
primaryStage.setScene(scene);
primaryStage.show();
ObservableList<String> data = FXCollections.observableArrayList(
"chocolate", "salmon", "gold", "coral", "darkorchid",
"darkgoldenrod", "lightsalmon", "black", "rosybrown", "blue",
"blueviolet", "brown");
cb.setItems(data);
Callback<ListView<String>, ListCell<String>> factory = new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> list) {
return new ColorRectCell();
}
};
cb.setCellFactory(factory);
Callback<ListView<String>, ListCell<String>> factoryTooltip = new Callback<ListView<String>, ListCell<String>>() {
#Override
public ListCell<String> call(ListView<String> list) {
return new ColorRectTooltipCell();
}
};
cb.setButtonCell(factoryTooltip.call(null));
}
static class ColorRectTooltipCell extends ColorRectCell {
#Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (item != null) {
Tooltip.install(this.getParent(), new Tooltip(item));
}
}
}

To Hide JavaFx fxml or JavaFx swing application to System Tray

I want to develop a client app for website .
I want the app to reside in system tray when minimised.
I dont know how to accomplish this task .
Is their any example for this type of operation.
The key here is to set the implicit exit to false Platform.setImplicitExit(false);
Also is important to show and hide the stage in a new thread.
Platform.runLater(new Runnable() {
#Override
public void run() {
stage.show();
}
});
Platform.runLater(new Runnable() {
#Override
public void run() {
stage.hide();
}
});
Next, the whole code:
import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
import javax.imageio.ImageIO;
/**
*
* #author alvaro
*/
public class TrayTest extends Application {
private boolean firstTime;
private TrayIcon trayIcon;
public static void main(String[] args)
{
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
createTrayIcon(stage);
firstTime = true;
Platform.setImplicitExit(false);
Scene scene = new Scene(new Group(), 800, 600);
stage.setScene(scene);
stage.show();
}
public void createTrayIcon(final Stage stage) {
if (SystemTray.isSupported()) {
// get the SystemTray instance
SystemTray tray = SystemTray.getSystemTray();
// load an image
java.awt.Image image = null;
try {
URL url = new URL("http://www.digitalphotoartistry.com/rose1.jpg");
image = ImageIO.read(url);
} catch (IOException ex) {
System.out.println(ex);
}
stage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
hide(stage);
}
});
// create a action listener to listen for default action executed on the tray icon
final ActionListener closeListener = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
System.exit(0);
}
};
ActionListener showListener = new ActionListener() {
#Override
public void actionPerformed(java.awt.event.ActionEvent e) {
Platform.runLater(new Runnable() {
#Override
public void run() {
stage.show();
}
});
}
};
// create a popup menu
PopupMenu popup = new PopupMenu();
MenuItem showItem = new MenuItem("Show");
showItem.addActionListener(showListener);
popup.add(showItem);
MenuItem closeItem = new MenuItem("Close");
closeItem.addActionListener(closeListener);
popup.add(closeItem);
/// ... add other items
// construct a TrayIcon
trayIcon = new TrayIcon(image, "Title", popup);
// set the TrayIcon properties
trayIcon.addActionListener(showListener);
// ...
// add the tray image
try {
tray.add(trayIcon);
} catch (AWTException e) {
System.err.println(e);
}
// ...
}
}
public void showProgramIsMinimizedMsg() {
if (firstTime) {
trayIcon.displayMessage("Some message.",
"Some other message.",
TrayIcon.MessageType.INFO);
firstTime = false;
}
}
private void hide(final Stage stage) {
Platform.runLater(new Runnable() {
#Override
public void run() {
if (SystemTray.isSupported()) {
stage.hide();
showProgramIsMinimizedMsg();
} else {
System.exit(0);
}
}
});
}
}
As far as I know it will be possible in JFX 8. Right now the best solution is to embed your application into AWT and hide the AWT window itself.

TitledPane - Event

I have two distinct components: a TableView and a TitledPane next to the table.
What I´m trying to do is to redimension the tableview but only when the titledpane expands or collapse.
When the titledpane collapse the tableview gets bigger and when it expands the tableview gets smaller.
I don´t know what action should I take.
Anybody knows the solution?
Regards
Check out the sample code below:
import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TitledPane;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class MyDemo extends Application {
private TableView<Person> tableview = new TableView<Person>();
// Suppose your preferred height values for those 2 component are as follows:
private double TABLE_MIN_HEIGHT = 30.0;
private double TABLE_MAX_HEIGHT = 500.0;
private double TITLED_PANE_HEIGHT; // will be determined
private final ObservableList<Person> data =
FXCollections.observableArrayList(
new Person("Jacob", "Smith", "jacob.smith#example.com"),
new Person("Isabella", "Johnson", "isabella.johnson#example.com"),
new Person("Ethan", "Williams", "ethan.williams#example.com"),
new Person("Emma", "Jones", "emma.jones#example.com"),
new Person("Michael", "Brown", "michael.brown#example.com"));
public static void main(String[] args) {
Application.launch(args);
}
#Override
public void start(Stage stage) {
TableColumn firstNameCol = new TableColumn("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("firstName"));
TableColumn lastNameCol = new TableColumn("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<Person, String>("lastName"));
TableColumn emailCol = new TableColumn("Email");
emailCol.setMinWidth(200);
emailCol.setCellValueFactory(new PropertyValueFactory<Person, String>("email"));
tableview.setItems(data);
tableview.getColumns().addAll(firstNameCol, lastNameCol, emailCol);
final TitledPane titledPane = new TitledPane("TitledPane", new Text("Content\n\n\n\n"));
titledPane.setAnimated(false); // we need to temporarily disable
// animation to get the titledpanes computed height correctly.
// Force to min height of table view
tableview.setMaxHeight(TABLE_MIN_HEIGHT);
tableview.setMinHeight(TABLE_MIN_HEIGHT);
// Here you have 2 options
int option = 2;
if (option == 1) {
// 1st simply force the table view height to its preferred max value
// when the titled pane's expanded property changed:
titledPane.expandedProperty().addListener(new ChangeListener<Boolean>() {
#Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
tableview.setMaxHeight(newValue ? TABLE_MIN_HEIGHT : TABLE_MAX_HEIGHT);
tableview.setMinHeight(newValue ? TABLE_MIN_HEIGHT : TABLE_MAX_HEIGHT);
}
});
} else if (option == 2) {
// 2nd. Similar to first but with "animation". Here observe height changes of titled pane:
titledPane.heightProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
tableview.setMaxHeight(TABLE_MAX_HEIGHT - (TABLE_MAX_HEIGHT * (newValue.doubleValue() / TITLED_PANE_HEIGHT)));
tableview.setMinHeight(TABLE_MAX_HEIGHT - (TABLE_MAX_HEIGHT * (newValue.doubleValue() / TITLED_PANE_HEIGHT)));
}
});
}
HBox hBox = new HBox(10);
hBox.getChildren().addAll(tableview, titledPane);
Scene scene = new Scene(hBox);
stage.setTitle("Table View Sample");
stage.setWidth(650);
stage.setHeight(700);
stage.setScene(scene);
TITLED_PANE_HEIGHT = titledPane.getHeight();
System.out.println("TITLED_PANE_HEIGHT = " + TITLED_PANE_HEIGHT);
stage.show();
// Determine the titledPane computed height value after stage has been shown.
TITLED_PANE_HEIGHT = titledPane.getHeight();
System.out.println("TITLED_PANE_HEIGHT = " + TITLED_PANE_HEIGHT);
// .. then enable animation
titledPane.setAnimated(true);
}
public static class Person {
private final SimpleStringProperty firstName;
private final SimpleStringProperty lastName;
private final SimpleStringProperty email;
private Person(String fName, String lName, String email) {
this.firstName = new SimpleStringProperty(fName);
this.lastName = new SimpleStringProperty(lName);
this.email = new SimpleStringProperty(email);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String fName) {
firstName.set(fName);
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String fName) {
lastName.set(fName);
}
public String getEmail() {
return email.get();
}
public void setEmail(String fName) {
email.set(fName);
}
}
}
It is demo, improve it according to your needs. There maybe other approaches as well. HTH.

Resources