JavaFX application doesn't close with swing content - java

I try to add Swing component to JavaFX application. I create SwingNode object with JButton but don't add this element to main Scene. After closing main stage, application stay running. What I need to do to fix this?
Example here:
public class SwingFx extends Application {
#Override
public void start(Stage stage) {
final SwingNode swingNode = new SwingNode();
createAndSetSwingContent(swingNode);
AnchorPane pane1 = new AnchorPane();
AnchorPane pane2 = new AnchorPane();
pane1.getChildren().add(swingNode);
stage.setScene(new Scene(pane2, 100, 50));
stage.show();
}
private void createAndSetSwingContent(final SwingNode swingNode) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
swingNode.setContent(new JButton("Click me!"));
}
});
}
public static void main(String[] args) {
launch(args);
}
}

I don't know why it happens, but I can give you some dirty solution to fix it. Application stay running after closing if you create SwingNode and don't add it to Scene. So you need to add SwingNode to Scene, but with zero size. This must fix your problem.
Example:
public class SwingFx extends Application {
#Override
public void start(Stage stage) {
// create pane with SwingNode
final SwingNode swingNode = new SwingNode();
createAndSetSwingContent(swingNode);
StackPane paneWithSwing = new StackPane(swingNode);
// create invisible pane to initialize SwingPane in Scene
Pane invisiblePane = new Pane(paneWithSwing);
invisiblePane.setPrefWidth(0);
invisiblePane.setPrefHeight(0);
invisiblePane.setOpacity(0);
// create Scene without visible SwingPane
Button button = new Button("Set SwingNode");
button.setOnAction(event -> {
invisiblePane.getChildren().clear();
stage.getScene().setRoot(paneWithSwing);
});
StackPane originalPane = new StackPane(invisiblePane, button);
stage.setScene(new Scene(originalPane, 320, 180));
stage.show();
}
private void createAndSetSwingContent(final SwingNode swingNode) {
SwingUtilities.invokeLater(() -> swingNode.setContent(new JButton("Click me!")));
}
public static void main(String[] args) {
launch(args);
}
}

Related

Cannot find a way to switch scenes with a button from class JavaFX

I'm trying to make a my scene switch to another when you click my button
My problem is in my second button in my class I am not sure what to put in it, I can't set the stage from inside that button because it is in another method I need to set about 10 different scenes, very confused any help is appreciated its a school culminating -_-. (If there is any better way to make a program that changes picture please inform me thank you!)
public class MainStage extends Application {
SceneSwitch switcher1= new SceneSwitch();
MediaPlayer mp3;
String i="file:///C://NetbeanFiles//plane.jpg";
Image pic=new Image(i);
#Override
public void start(Stage primaryStage) {
Media musicfile=new Media("file:///C://NetbeanFiles//Stereo.mp3");
mp3= new MediaPlayer(musicfile);
mp3.setAutoPlay(true);
mp3.setVolume(0.05);
ImageView view = new ImageView(pic);
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
primaryStage.setScene(switcher1.Switcher());
}
});
BorderPane pane = new BorderPane();
pane.setCenter(view);
btn.setPadding(new Insets(10 ,10, 10, 10));
pane.setTop(btn);
Scene scene = new Scene(pane, 1920, 1080);
//how to keep button centered last number is X
pane.setMargin(btn, new Insets(10, 10, 10, 875));
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
//End of MAINSTAGE
//Start of SCENESWITCH class
public class SceneSwitch {
int j=0;
String i="file:///C://NetbeanFiles//planet.jpg";
ArrayList<String> Hello= new ArrayList<String>();
public SceneSwitch(){
Hello.add("file:///C://NetbeanFiles//planet.jpg");
`Hello.add("file:///C://NetbeanFiles//download.jpg");
}
public Scene Switcher(){
ImageView view = new ImageView(Hello.get(j));
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
//**HERE IS MY PROBLEM NOT SURE WHAT TO PUT IN HERE**
}
});
BorderPane pane = new BorderPane();
pane.setCenter(view);
btn.setPadding(new Insets(10 ,10, 10, 10));
pane.setTop(btn);
Scene scene = new Scene(pane, 1920, 1080);
//how to keep button centered last number is X
pane.setMargin(btn, new Insets(10, 10, 10, 875));
return scene;
}
}

javaFX launch app error

i'm trying to run this simple Javafx code:
public class Javafx extends Application
{
Stage window;
Scene scene1,scene2;
public static void main(String[] args) {
launch(args);
}
public void start(Stage primaryStage) throws Exception{
window = primaryStage;
Label label1 = new Label("click here to go to scene 2");
Button button1 = new Button("click here");
button1.setOnAction(e-> window.setScene(scene2));
VBox layout1 = new VBox(15);
layout1.getChildren().addAll(label1,button1);
scene1 = new Scene(layout1,700,900);
Label label2 = new Label("get back to scene1");
Button button2 = new Button("press");
button2.setOnAction(e-> window.setScene(scene1));
StackPane layout2 = new StackPane();
label2.setRotate(70);
layout2.getChildren().addAll(label2,button2);
scene2 = new Scene(layout2,500,500);
window.setScene(scene1);
window.setTitle("Java FX");
window.show();
}
}
but for some reason after i'm closing the app and rerun it,iv'e got an error:
application luanch must not called more than once.
as far as i can tell,the launch app called only once,but the only way for me to rerun it again is to reset first the JVM .
can anyone tell me how can i overcome this?
i'm using Bluej if that's matter,

JavaFX - Constraints in programmatically scrolling a ScrollPane

I am trying to scroll a ScrollPane that contains an XYChart via code.
#FXML
private ScrollPane graphSP;
Scrolling it, for instance, to the half-way point works with this sequence:
Stage stage = new Stage();
stage.show();
graphSP.setHvalue(.5);
The problem is, if I place that call to setHvalue() elsewhere, it just does nothing.
So wondering, what are the constraints to actually cause the ScrollPane to scroll? Or, where can I call setHvalue() in my program.
You need to set the Hvalue/Vvalue of the ScrollPane after the scene is visible i.e. stage.isShowing() is true.
EDIT
One way to call it is after the stage.show() is called.
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
LineChart<Number, Number> chart = new LineChart<>(new NumberAxis(), new NumberAxis());
ScrollPane scrollPane = new ScrollPane(chart);
primaryStage.setScene(new Scene(scrollPane, 300, 300));
primaryStage.show();
scrollPane.setVvalue(0.5);
scrollPane.setHvalue(0.5);
}
public static void main(String[] args) {
launch(args);
}
}
But, there may be cases where a reference to stage is not available. In those case you can use the following :
public class Main extends Application {
#Override
public void start(Stage primaryStage) throws Exception {
LineChart<Number, Number> chart = new LineChart<>(new NumberAxis(), new NumberAxis());
ScrollPane scrollPane = new ScrollPane(chart);
primaryStage.setScene(new Scene(scrollPane, 300, 300));
scrollPane.getScene().getWindow().showingProperty().addListener((observable, oldValue, newValue) -> {
if (newValue) {
scrollPane.setVvalue(0.5);
scrollPane.setHvalue(0.5);
}
});
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}

How to Achieve One Menubar for more then one scenes in javaFx

I am basically new to Java FX 2.
Scenario:
I have 3 Scenes and I want a way to add menu-bar such that I don't i don't want to explicitly remove the menu bar from previous scene and add it to new one. Like Some thing a Parent Scene or some way menu-bar is attached to Stage. I mean menu-bar is added just one time and always be present whatever scene is in front or not.
If This is Possible How Can I do this.
Here is the Default Example Provided by Oracle Docs of JavaFX http://docs.oracle.com/javafx/2/ui_controls/MenuSample.java.html
public class Main extends Application {
final ImageView pic = new ImageView();
final Label name = new Label();
final Label binName = new Label();
final Label description = new Label();
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) {
stage.setTitle("Menu Sample");
Scene scene = new Scene(new VBox(), 400, 350);
scene.setFill(Color.OLDLACE);
MenuBar menuBar = new MenuBar();
// --- Graphical elements
final VBox vbox = new VBox();
vbox.setAlignment(Pos.CENTER);
vbox.setSpacing(10);
vbox.setPadding(new Insets(0, 10, 0, 10));
makeContentsForVBox();// in this vBox area will be fill with name pic desrciption
vbox.getChildren().addAll(name, binName, pic, description); // name is lable
// --- Menu File
Menu menuFile = new Menu("File");
MenuItem add = new MenuItem("Shuffle",
new ImageView(new Image(getClass().getResourceAsStream("new.png"))));
add.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
shuffle();
vbox.setVisible(true);
}
});
MenuItem clear = new MenuItem("Clear");
clear.setAccelerator(KeyCombination.keyCombination("Ctrl+X"));
clear.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
vbox.setVisible(false);
}
});
MenuItem exit = new MenuItem("Exit");
exit.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent t) {
System.exit(0);
}
});
menuFile.getItems().addAll(add, clear, new SeparatorMenuItem(), exit);
((VBox) scene.getRoot()).getChildren().addAll(menuBar, vbox);
stage.setScene(scene);
stage.show();
}
}
So Here menuBar is added to a scene. if i swap the scene and bring an other scene in front ... What will i do. i think I remove menuBar from this scene and add to other or simply add to new one. so every time i have to do this when i change. Is there any way to avoid this??
The approach I would prefer is to use a Scene with BorderPane as its root
scene.setRoot(borderPane);
You can add the MenuBar to the top of the BorderPane and at its Center you can place SplitPane
BorderPane borderPane = new BorderPane();
borderPane.setTop(menuBar);
borderPane.setCenter(splitPane);
Whenever you need to switch to WebView just replace it with SplitPane :
borderPane.setCenter(webView);
Following this approach, your MenuBar will always remain on TOP and you can switch between SplitPane and WebView

Switching scene in javaFX

I have problem when trying to close current scene and open up another scene when menuItem is selected. My main stage is coded as below:
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Shop Management");
Pane myPane = (Pane)FXMLLoader.load(getClass().getResource
("createProduct.fxml"));
Scene myScene = new Scene(myPane);
primaryStage.setScene(myScene);
primaryStage.show();
}
Then within createProduct.fxml, when menuItem is onclick, it will perform this:
public void gotoCreateCategory(ActionEvent event) throws IOException {
Stage stage = new Stage();
stage.setTitle("Shop Management");
Pane myPane = null;
myPane = FXMLLoader.load(getClass().getResource("createCategory.fxml"));
Scene scene = new Scene(myPane);
stage.setScene(scene);
stage.show();
}
It does opened up createCategory.fxml. However, the previous panel which is createProduct.fxml does not close. I know there's something called stage.close() to do this but I have no idea where to implement it since I not passing the scene from main right from the start. I wonder how should I fix this.
Thanks in advance.
You have to make some changes in start method, like..
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Shop Management");
FXMLLoader myLoader = new FXMLLoader(getClass().getResource("createProduct.fxml"));
Pane myPane = (Pane)myLoader.load();
CreateProductController controller = (CreateProductController) myLoader.getController();
controller.setPrevStage(primaryStage);
Scene myScene = new Scene(myPane);
primaryStage.setScene(myScene);
primaryStage.show();
}
and your CreateProductController.java will be,
public class CreateProductController implements Initializable {
Stage prevStage;
public void setPrevStage(Stage stage){
this.prevStage = stage;
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
public void gotoCreateCategory(ActionEvent event) throws IOException {
Stage stage = new Stage();
stage.setTitle("Shop Management");
Pane myPane = null;
myPane = FXMLLoader.load(getClass().getResource("createCategory.fxml"));
Scene scene = new Scene(myPane);
stage.setScene(scene);
prevStage.close();
stage.show();
}
}
You have multiple ways to solve your problem, few of them I tell you. What I understood from your question is that you want to create an application which contains a navigation (menu bar) on the top and by using it user can switch to any screen.
The easiest method is to make your Navigation Bar available globally, either by you make it static or by passing it to screens, or by any other method. Second, make a single screen (say Border Pane) and load other screens on it (its center).
You can also use spring integration in project so that it provide you better injection of controllers. See Ref : http://www.zenjava.com/2011/10/25/views-within-views-controllers-within-controllers/
You can also create your own single screen controller and manage other screens using that.
See Ref: https://blogs.oracle.com/acaicedo/entry/managing_multiple_screens_in_javafx1
But for this (above) you have to change or update your current architecture.
you can get the current open window/stage from the fx:id . just make sure you have an item in your createProduct.fxml that has fx:id like below
<TextField fx:id="username" labelFloat="true" layoutX="80.0" layoutY="300.0" prefHeight="32.0" prefWidth="260.0" promptText="Login Username" />
Hope you see the fx:id attribute.
Then in your start controller, leave as it is
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("Shop Management");
Pane myPane = (Pane)FXMLLoader.load(getClass().getResource("createProduct.fxml"));
Scene myScene = new Scene(myPane);
primaryStage.setScene(myScene);
primaryStage.show();
}
Then in your CreateProductController.java
//make sure you import the javafx item you have used, eg have used TextField
import javafx.scene.control.TextField;
public class CreateProductController implements Initializable {
// make sure the variable has the same type as the item in the fxml "TextField" and same name "username"
#FXML
private TextField username;
//we use the above variable since its referencing the window to which it belongs because of the fx:id attribute, then we close it
private void closeStage()
{
((Stage) username.getScene().getWindow()).close();
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
public void gotoCreateCategory(ActionEvent event) throws IOException {
closeStage();// we close the old stage
Stage stage = new Stage();
stage.setTitle("Shop Management");
Pane myPane = null;
myPane = FXMLLoader.load(getClass().getResource("createCategory.fxml"));
Scene scene = new Scene(myPane);
stage.setScene(scene);
stage.show();
}
}

Categories

Resources