I am a java beginner, i used eclipse to make a gridbaglayout:
import java.awt.EventQueue;
import javax.swing.JFrame;
import java.awt.GridBagLayout;
import javax.swing.JLabel;
import java.awt.GridBagConstraints;
public class test4 {
public static JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
test4 window = new test4();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public test4() {
initialize();
}
/**
* Initialize the contents of the frame.
* #return
*/
public static void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 137, 89);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagLayout gridBagLayout = new GridBagLayout();
gridBagLayout.columnWidths = new int[]{0, 0};
gridBagLayout.rowHeights = new int[]{0, 0};
gridBagLayout.columnWeights = new double[]{0.0, Double.MIN_VALUE};
gridBagLayout.rowWeights = new double[]{0.0, Double.MIN_VALUE};
frame.getContentPane().setLayout(gridBagLayout);
JLabel lblNewLabel = new JLabel("Label");
GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
gbc_lblNewLabel.gridx = 0;
gbc_lblNewLabel.gridy = 0;
frame.getContentPane().add(lblNewLabel, gbc_lblNewLabel);
}
}
i want to use {lblNewLabel.setText("test");} in {public static void main(String[] args) } or in {private static set(){lblNewLabel.setText("test");}} but it did not work. What should i do? Thanks for any help.
public class MyNiceApplication {
private Label niceLabel;
void initialize(){...} //Frame init...
public void setNiceLabelText(String text){
niceLabel.setText(text);
}
}
public static void main(String[] args) {
MyNiceApplication app = new MyNiceApplication();
app.setNiceLabelText("New LabelText");
}
Related
I'm building a UI for a Simulator running in background. Since this Simulator may not hold for a long time, it of course has to be in a separate thread from the JavaFx Thread. I want to start, pause, resume and stop/terminate the Simulator when the corresponding button is clicked.
The service class that advances the simulator looks like this:
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
public class SimulatorService extends Service<Void> {
private Simulator simulator;
private long cycleLengthMS = 1000;
private final AtomicBoolean simulatorStopped = new AtomicBoolean(false);
public SimulatorService(Simulator simulator){
this.simulator = simulator;
}
#Override
protected Task<Void> createTask() {
return new Task<>() {
#Override
protected Void call() {
System.out.println("Requested start of Simulator");
int state;
do {
// advance
state = simulator.nextStep();
try {
TimeUnit.MILLISECONDS.sleep(cycleLengthMS);
if(simulatorStopped.get()){
super.cancel();
}
} catch (InterruptedException e) {
return null;
}
}
while (state == 0 && !simulatorStopped.get());
return null;
}
};
}
#Override
public void start(){
if(getState().equals(State.READY)){
simulatorStopped.set(false);
super.start();
}
else if(getState().equals(State.CANCELLED)){
simulatorStopped.set(false);
super.restart();
}
}
#Override
public boolean cancel(){
if(simulatorStopped.get()){
simulatorStopped.set(true);
return false;
} else{
simulatorStopped.set(true);
return true; //if value changed
}
}
}
The Simulator starts the Service if a button on the GUI is pressed:
import javafx.application.Platform;
import java.util.concurrent.atomic.AtomicInteger;
public class Simulator {
Model model;
private final SimulatorService simulatorService;
public Simulator(Model model){
this.model = model;
simulatorService = new SimulatorService(this);
}
public int nextStep(){
final AtomicInteger res = new AtomicInteger(0);
Platform.runLater(new Thread(()-> {
res.set(model.nextStep());
}));
return res.get();
}
public boolean stopSimulationService() throws IllegalStateException{
return simulatorService.cancel();
}
public void startSimulationService() throws IllegalStateException{
simulatorService.start();
}
}
Parts of the window are redrawn if a observed value in the model changes:
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
public class Model {
private final IntegerProperty observedValue = new SimpleIntegerProperty(0);
public int nextStep() {
observedValue.set(observedValue.get() + 1);
return observedValue.get() > 500000 ? 1 : 0;
}
public int getObservedValue() {
return observedValue.get();
}
public IntegerProperty observedValueProperty() {
return observedValue;
}
public void setObservedValue(int observedValue) {
this.observedValue.set(observedValue);
}
}
The redraw happens in another class:
import javafx.beans.value.ChangeListener;
public class ViewController {
private View view;
private Simulator simulator;
private Model model;
public ViewController(Simulator simulator) {
this.simulator = simulator;
this.view = new View();
setModel(simulator.model);
view.nextStep.setOnMouseClicked(click -> {
simulator.nextStep();
});
view.startSim.setOnMouseClicked(click -> {
simulator.startSimulationService();
});
view.stopSim.setOnMouseClicked(click ->{
simulator.stopSimulationService();
});
}
public View getView() {
return view;
}
private final ChangeListener<Number> observedValueListener = (observableValue, oldInt, newInt) -> {
view.updateView(newInt.intValue());
};
public void setModel(Model m) {
this.model = m;
m.observedValueProperty().addListener(observedValueListener);
}
}
The corresponding view:
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
public class View extends BorderPane {
Button nextStep = new Button("next step");
Button startSim = new Button("start");
Button stopSim = new Button("stop");
GridPane buttons = new GridPane();
Text num = new Text();
public View(){
buttons.add(nextStep,0,0);
buttons.add(startSim,0,1);
buttons.add(stopSim,0,2);
buttons.setAlignment(Pos.BOTTOM_LEFT);
setCenter(buttons);
setTop(num);
}
public void updateView(int num){
this.num.setText("" + num);
}
}
Main:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws Exception {
ViewController c = new ViewController(new Simulator(new Model()));
Scene scene = new Scene(c.getView(),200,200);
stage.setScene(scene);
stage.show();
}
}
I am trying to run an Infinite loop in my JavaFX app.
An infinite while loop is present in my code in the Kulta.java file.
This loop actually freezes my app.
While the same thing works when I port the app to normal javax.swing.
Now since java.lang.Thread doesn't work for javafx, I came accross javafx.concurrent.Task,
which is not working as intended. As one of the main features of multithreading, i.e. running an infinite loop in a GUI app, is not served properly, please help me with the solution.
This is my code:
Urania.java
import java.awt.Toolkit;
import java.awt.Dimension;
import javax.swing.SwingUtilities;
import static javax.swing.WindowConstants.EXIT_ON_CLOSE;
public class Urania {
public static final Dimension DIMENSION = Toolkit.getDefaultToolkit().getScreenSize();
public static void main(String[] args) {
SwingUtilities.invokeLater(
new Runnable() {
#Override
public void run() {
Kulta kulta = new Kulta();
kulta.setTitle("Abha K Pauri");
kulta.setSize(DIMENSION.width/2, DIMENSION.height/2);
kulta.setLocationRelativeTo(null);
kulta.setDefaultCloseOperation(EXIT_ON_CLOSE);
kulta.setVisible(true);
}
}
);
}
}
And here is my JFrame in which I have embedded my JavaFX app.
Kulta.java
import javax.swing.JFrame
import javafx.embed.swing.JFXPanel;
import javafx.application.Platform;
import javafx.scene.Scene;
import javafx.scene.layout.BorderPane;
import javafx.scene.control.Button;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.concurrent.Task;
public class Kulta extends JFrame {
private JFXPanel fxpanel;
private Scene scene;
private BorderPane borderpane;
private Button button;
public static final String INVOKE = "INVOKE";
public static final String INTERRUPT = "INTERRUPT";
public static final String[] COLORS = new String[]{"yellow", "pink", "green", "blue", "orange"};
public Kulta() {
fxpanel = new JFXPanel();
add(fxpanel);
Platform.runLater(
new Runnable() {
#Override
public void run() {
Kulta.this.setScene();
Kulta.this.setButton();
Kulta.this.setListener();
}
}
);
}
private void setScene() {
borderpane = new BorderPane();
scene = new Scene(borderpane);
fxpanel.setScene(scene);
}
private void setButton() {
button = new Button(INVOKE);
borderpane.setTop(button);
}
private void setListener() {
Event event = new Event();
button.setOnAction(event);
}
private class Event implements EventHandler<ActionEvent> {
#Override
public void handle(ActionEvent event) {
boolean flag = true;
Task<Void> onInvoke = new Task<Void>() {
#Override
public Void call() {
int count = 0;
flag = true;
button.setText(INTERRUPT);
/* This loop freezes the app. */
while(flag) {
borderpane.setStyle("-fx-color: "+COLORS[count]+";");
count++;
if(count == COLORS.length)
count = 0;
}
return null;
}
};
Task<Void> onInterrupt = new Task<Void>() {
#Override
public Void call() {
button.setText(INVOKE);
if(flag)
flag = false; // This will stop the onInvoke thread
return null;
}
};
Task<Void> change = new Task<Void>() {
#Override
public Void call() {
if(button.getText().equals(INVOKE))
onInvoke().run();
else if(button.getText().equals(INTERRUPT))
onInterrupt().run();
}
};
change.run();
}
}
}
How should I write the loop in order to not let the app freeze.
Any code, solution, link or any help in any form will help a lot.
Thanks in advance.
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;
}
}
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.
I am trying to get my head around the JavaFX stuff...
My program is a WindowBuilder based Gui, and I want a JavaFX graph, and a JavaFX live video-feed displayed in my app.
How do I implement it in my code? I have tried this, but I couldn't get it runnning.
The data feed isnt the problem. I just need to view it inside my JFrame as small squares...
Confused now :(
Here is my code: (I am sorry that it is a tad long, but I blame the examplecode from JavaFX :p
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.UIManager;
import java.awt.Canvas;
import java.awt.SystemColor;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import javax.swing.UIManager.*;
/**
* #author
*
*/
public class MyClientApp extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
protected static final String BufferedWriter = null;
JFrame frame;
private JTextField textFieldUsername;
/**
* Create the application.
*/
public MyClientApp(BufferedWriter serverDataOut, BufferedReader serverDataIn) {
initialize();
}
/**
* Initialize the contents of the frame.
*
* #param serverDataOut
*
*/
private void initialize() {
try {
for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (Exception e) {
// Nimbus Theme not avaliable
}
frame = new JFrame();
frame.setResizable(false);
frame.setTitle("*********** My Program ***********");
frame.setBounds(320, 130, 730, 570);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
Canvas canvasTemp = new Canvas();
canvasTemp.setBackground(SystemColor.window);
canvasTemp.setBounds(6, 277, 380, 255);
frame.getContentPane().add(canvasTemp);
Canvas canvasLevel = new Canvas();
canvasLevel.setBackground(SystemColor.window);
canvasLevel.setBounds(6, 10, 380, 255);
frame.getContentPane().add(canvasLevel);
}
public JFrame frame() {
return frame;
}
}
And here is the main file to get it running for you guys... :
Client.java
import java.io.IOException;
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
MyClientApp window = new MyClientApp(null, null);
window.frame.setVisible(true);
}
}
The code I want to implement is:
AdvancedLineChartSample.java (from JavaFX)
/**
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*/
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import java.util.ArrayList;
import java.util.List;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Side;
import javafx.scene.Node;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.chart.XYChart.Series;
import javafx.util.Duration;
/**
* An advanced line chart with a variety of actions and settable properties.
*
* #see javafx.scene.chart.LineChart
* #see javafx.scene.chart.Chart
* #see javafx.scene.chart.NumberAxis
* #see javafx.scene.chart.XYChart
*/
public class AdvancedLineChartSample extends Application {
private void init(Stage primaryStage) {
Group root = new Group();
primaryStage.setScene(new Scene(root));
root.getChildren().add(createChart());
}
protected LineChart<Number, Number> createChart() {
final NumberAxis xAxis = new NumberAxis();
final NumberAxis yAxis = new NumberAxis();
final LineChart<Number,Number> lc = new LineChart<Number,Number>(xAxis,yAxis);
// setup chart
lc.setTitle("Temp Chart");
xAxis.setLabel("tid");
yAxis.setLabel("temp");
// add starting data
XYChart.Series<Number,Number> series = new XYChart.Series<Number,Number>();
series.setName("Dataset 1");
series.getData().add(new XYChart.Data<Number,Number>(20d, 50d));
series.getData().add(new XYChart.Data<Number,Number>(40d, 80d));
series.getData().add(new XYChart.Data<Number,Number>(50d, 90d));
series.getData().add(new XYChart.Data<Number,Number>(70d, 30d));
series.getData().add(new XYChart.Data<Number,Number>(170d, 122d));
lc.getData().add(series);
return lc;
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
}
public static void main(String[] args) { launch(args);
}
}
and the StreamingMediaPlayer.java (from JavaFX):
/**
* Copyright (c) 2008, 2012 Oracle and/or its affiliates.
* All rights reserved. Use is subject to license terms.
*/
import javafx.application.Application;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.application.Platform;
import javafx.beans.InvalidationListener;
import javafx.beans.Observable;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Priority;
import javafx.scene.layout.Region;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaPlayer.Status;
import javafx.scene.media.MediaView;
import javafx.util.Duration;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.animation.ParallelTransition;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
/**
* A media player with controls for play, pause, stop, seek, and volume. This media player is playing media via HTTP Live Streaming, also known as HLS.
*
* #see javafx.scene.media.MediaPlayer
* #see javafx.scene.media.Media
*/
public class StreamingMediaPlayer extends Application {
private static final String MEDIA_URL = "http://download.oracle.com/otndocs/products/javafx/JavaRap/prog_index.m3u8";
private MediaPlayer mediaPlayer;
private void init(Stage primaryStage) {
Group root = new Group();
primaryStage.setScene(new Scene(root));
mediaPlayer = new MediaPlayer(new Media(MEDIA_URL));
mediaPlayer.setAutoPlay(true);
PlayerPane playerPane = new PlayerPane(mediaPlayer);
playerPane.setMinSize(480, 360);
playerPane.setPrefSize(480, 360);
playerPane.setMaxSize(480, 360);
// getStylesheets().add("ensemble/samples/media/OverlayMediaPlayer.css");
root.getChildren().add(playerPane);
}
public void play() {
Status status = mediaPlayer.getStatus();
if (status == Status.UNKNOWN || status == Status.HALTED) {
return;
}
if (status == Status.PAUSED || status == Status.STOPPED || status == Status.READY) {
mediaPlayer.play();
}
}
#Override public void stop() {
mediaPlayer.stop();
}
static class PlayerPane extends BorderPane {
private MediaPlayer mp;
private MediaView mediaView;
private final boolean repeat = false;
private boolean stopRequested = false;
private boolean atEndOfMedia = false;
private Duration duration;
private Slider timeSlider;
private Label playTime;
private Slider volumeSlider;
private HBox mediaTopBar;
private HBox mediaBottomBar;
private ParallelTransition transition = null;
#Override protected void layoutChildren() {
if (mediaView != null && getBottom() != null) {
mediaView.setFitWidth(getWidth());
mediaView.setFitHeight(getHeight() - getBottom().prefHeight(-1));
}
super.layoutChildren();
if (mediaView != null) {
mediaView.setTranslateX((((Pane)getCenter()).getWidth() - mediaView.prefWidth(-1)) / 2);
mediaView.setTranslateY((((Pane)getCenter()).getHeight() - mediaView.prefHeight(-1)) / 2);
}
}
#Override protected double computeMinWidth(double height) {
return mediaBottomBar.prefWidth(-1);
}
#Override protected double computeMinHeight(double width) {
return 200;
}
#Override protected double computePrefWidth(double height) {
return Math.max(mp.getMedia().getWidth(), mediaBottomBar.prefWidth(height));
}
#Override protected double computePrefHeight(double width) {
return mp.getMedia().getHeight() + mediaBottomBar.prefHeight(width);
}
#Override protected double computeMaxWidth(double height) { return Double.MAX_VALUE; }
#Override protected double computeMaxHeight(double width) { return Double.MAX_VALUE; }
public PlayerPane(final MediaPlayer mp) {
this.mp = mp;
setId("player-pane");
mediaView = new MediaView(mp);
Pane mvPane = new Pane() { };
mvPane.setId("media-pane");
mvPane.getChildren().add(mediaView);
setCenter(mvPane);
mediaTopBar = HBoxBuilder.create()
.padding(new Insets(5, 10, 5, 10))
.alignment(Pos.CENTER)
.opacity(1)
.build();
BorderPane.setAlignment(mediaTopBar, Pos.CENTER);
mediaBottomBar = HBoxBuilder.create()
.padding(new Insets(5, 10, 5, 10))
.alignment(Pos.CENTER)
.opacity(1)
.build();
BorderPane.setAlignment(mediaBottomBar, Pos.CENTER);
mp.currentTimeProperty().addListener(new ChangeListener<Duration>() {
#Override
public void changed(ObservableValue<? extends Duration> observable, Duration oldValue, Duration newValue) {
updateValues();
}
});
mp.setOnPlaying(new Runnable() {
public void run() {
if (stopRequested) {
mp.pause();
stopRequested = false;
}
}
});
mp.setOnReady(new Runnable() {
public void run() {
duration = mp.getMedia().getDuration();
updateValues();
}
});
mp.setOnEndOfMedia(new Runnable() {
public void run() {
if (!repeat) {
stopRequested = true;
atEndOfMedia = true;
}
}
});
mp.setCycleCount(repeat ? MediaPlayer.INDEFINITE : 1);
// Time label
Label timeLabel = LabelBuilder.create()
.text("Time")
.minWidth(Control.USE_PREF_SIZE)
.textFill(Color.WHITE)
.build();
mediaTopBar.getChildren().add(timeLabel);
// Time slider
timeSlider = SliderBuilder.create()
.id("media-slider")
.minWidth(240)
.maxWidth(Double.MAX_VALUE)
.build();
timeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
if (timeSlider.isValueChanging()) {
// multiply duration by percentage calculated by slider position
if (duration != null) {
mp.seek(duration.multiply(timeSlider.getValue() / 100.0));
}
updateValues();
}
}
});
HBox.setHgrow(timeSlider, Priority.ALWAYS);
mediaTopBar.getChildren().add(timeSlider);
// Play label
playTime = LabelBuilder.create()
.prefWidth(130)
.minWidth(50)
.textFill(Color.WHITE)
.build();
mediaTopBar.getChildren().add(playTime);
// Volume label
Label volumeLabel = LabelBuilder.create()
.text("Vol")
.textFill(Color.WHITE)
.minWidth(Control.USE_PREF_SIZE)
.build();
mediaTopBar.getChildren().add(volumeLabel);
// Volume slider
volumeSlider = SliderBuilder.create()
.id("media-slider")
.prefWidth(120)
.maxWidth(Region.USE_PREF_SIZE)
.minWidth(30)
.build();
volumeSlider.valueProperty().addListener(new InvalidationListener() {
public void invalidated(Observable ov) {
}
});
volumeSlider.valueProperty().addListener(new ChangeListener<Number>() {
#Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
if (volumeSlider.isValueChanging()) {
mp.setVolume(volumeSlider.getValue() / 100.0);
}
}
});
mediaTopBar.getChildren().add(volumeSlider);
setTop(mediaTopBar);
final EventHandler<ActionEvent> backAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.seek(Duration.ZERO);
}
};
final EventHandler<ActionEvent> stopAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.stop();
}
};
final EventHandler<ActionEvent> playAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.play();
}
};
final EventHandler<ActionEvent> pauseAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
mp.pause();
}
};
final EventHandler<ActionEvent> forwardAction = new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
Duration currentTime = mp.getCurrentTime();
mp.seek(Duration.seconds(currentTime.toSeconds() + 5.0));
}
};
mediaBottomBar = HBoxBuilder.create()
.id("bottom")
.spacing(0)
.alignment(Pos.CENTER)
.children(
ButtonBuilder.create()
.id("back-button")
.text("Back")
.onAction(backAction)
.build(),
ButtonBuilder.create()
.id("stop-button")
.text("Stop")
.onAction(stopAction)
.build(),
ButtonBuilder.create()
.id("play-button")
.text("Play")
.onAction(playAction)
.build(),
ButtonBuilder.create()
.id("pause-button")
.text("Pause")
.onAction(pauseAction)
.build(),
ButtonBuilder.create()
.id("forward-button")
.text("Forward")
.onAction(forwardAction)
.build()
)
.build();
setBottom(mediaBottomBar);
}
protected void updateValues() {
if (playTime != null && timeSlider != null && volumeSlider != null && duration != null) {
Platform.runLater(new Runnable() {
public void run() {
Duration currentTime = mp.getCurrentTime();
playTime.setText(formatTime(currentTime, duration));
timeSlider.setDisable(duration.isUnknown());
if (!timeSlider.isDisabled() && duration. greaterThan(Duration.ZERO) && !timeSlider.isValueChanging()) {
timeSlider.setValue(currentTime.divide(duration).toMillis() * 100.0);
}
if (!volumeSlider.isValueChanging()) {
volumeSlider.setValue((int) Math.round(mp.getVolume() * 100));
}
}
});
}
}
private static String formatTime(Duration elapsed, Duration duration) {
int intElapsed = (int)Math.floor(elapsed.toSeconds());
int elapsedHours = intElapsed / (60 * 60);
if (elapsedHours > 0) {
intElapsed -= elapsedHours * 60 * 60;
}
int elapsedMinutes = intElapsed / 60;
int elapsedSeconds = intElapsed - elapsedHours * 60 * 60 - elapsedMinutes * 60;
if (duration.greaterThan(Duration.ZERO)) {
int intDuration = (int)Math.floor(duration.toSeconds());
int durationHours = intDuration / (60 * 60);
if (durationHours > 0) {
intDuration -= durationHours * 60 * 60;
}
int durationMinutes = intDuration / 60;
int durationSeconds = intDuration - durationHours * 60 * 60 - durationMinutes * 60;
if (durationHours > 0) {
return String.format("%d:%02d:%02d",
elapsedHours, elapsedMinutes, elapsedSeconds);
} else {
return String.format("%02d:%02d",
elapsedMinutes, elapsedSeconds);
}
} else {
if (elapsedHours > 0) {
return String.format("%d:%02d:%02d",
elapsedHours, elapsedMinutes, elapsedSeconds);
} else {
return String.format("%02d:%02d",
elapsedMinutes, elapsedSeconds);
}
}
}
}
#Override public void start(Stage primaryStage) throws Exception {
init(primaryStage);
primaryStage.show();
play();
}
public static void main(String[] args) { launch(args);
}
}
I'm sorry about the long code. Its just the samplecode from JavaFX. You find it here, and here.
That should be quite easy to solve. Let me explain it with the chart example that you've shown.
Add an instance of JFXPanel to your JFrame. In your examples, all components are added to a Stage, which is the JavaFX class to represent a window. So you don't need it here. Instead, you add the components that you want to use to the JFXPanel. See also here (function initAndShowGUI) how to do it.
In the init function of the example, a Scene is created as well as the chart itself. What you have to do to let the chart be shown is not much more than that - create a Scene, fill it with content and pass it to the JFXPanel that you already created.
With a minimum effort you can make your chart example run: Make sure that AdvancedLineChartSample.java is in your build path and that the function createChart is somehow accessible from your JFrame. Then add the chart to your code with something similar to the following snippet.
Group root=new Group();
Scene scene=new Scene(root);
myJFXPanel.setScene(scene);
root.getChildren().add(createChart());
This is just a very quick and dirty solution to run your example without any beautiful code and also I didn't test it. But hopefully it gives you a basic understanding of what's going on to encourage further experiments. By my own experience I can tell you that from this step on, there's a lot of fun to come with JavaFX 2.