javafx alert dialog on swing frame - java

I'm working on an application which is based on swing and javafx 8. In this create a frame in swing and jbutton use and jbutton action code is done in javafx 8 means use scene. in this a alert dialog create.but problem is that if i click anywhere except alert dialog then alert dialog hidden behind swing frame.i want javafx alert dialog keep on swing frame which i create.if i click ok on alert then action is goes to swing frame.
please suggest......
here is my code:
final JFXPanel fxPanel = new JFXPanel();
Platform.runLater(new Runnable() {
public void run() {
initFX(fxPanel);
}
private void initFX(JFXPanel fxPanel) {
// TODO Auto-generated method stub
Scene scene = createScene();
fxPanel.setScene(scene);
}
private Scene createScene() {
Group root = new Group();
Scene scene = new Scene(root);
Alert cn=new Alert(AlertType.CONFIRMATION);
cn.initStyle(StageStyle.UNDECORATED);
cn.setTitle(null);
cn.setHeaderText(null);
cn.setContentText(ProjectProps.rb.getString("msg.play.confirm"));
DialogPane dp=cn.getDialogPane();
dp.getStylesheets().add(getClass().getResource("login.css").toExternalForm());
dp.setStyle("-fx-border-color: black; -fx-border-width: 5px; ");
Optional<ButtonType> result=cn.showAndWait();
if(result.get()==ButtonType.OK){
System.out.println("ok button clicked:"+result.get());
k=0;
} else{
System.out.println("cancel clicked");
k=1;
}
return (scene);
}
});

I'm not sure to understand what you really want to do. Do you absolutely need a JavaFX alert in a swing application? JDialog works very well, and Alert and Dialogs works very well too in a JavaFX context.
Have you tried to set your Alert application modal with cn.initModality(Modality.APPLICATION_MODAL) ?
Maybe you can find you answer in this post : How to make a JFrame Modal in Swing java
This is the suggested code in the post:
final JDialog frame = new JDialog(parentFrame, frameTitle, true);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
I would create a new JDialog and set as parameter your main frame (parentFrame) and add your JFXPanel to its content.
frame.getContentPane.add(fxPanel)
You can use fxPanel.setScene(yourScene) to add FX content to your JDialog.
Example for the suggestion:
public class Main {
public static void main(String[] args) {
// create parent
JFrame parent = new JFrame("MainFrame");
parent.setSize(500, 500);
// center of screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
parent.setLocation(dim.width/2-parent.getSize().width/2, dim.height/2-parent.getSize().height/2);
parent.setVisible(true);
createDialog(parent);
}
private static void createDialog(JFrame parent) {
// create dialogs JFX content
BorderPane layout = new BorderPane();
layout.setTop(new Button("HELLO"));
layout.setBottom(new Button("IT'S ME"));
Scene scene = new Scene(layout);
JFXPanel dlgContent = new JFXPanel();
dlgContent.setScene(scene);
dlgContent.setPreferredSize(new Dimension(200, 200));
dlgContent.setVisible(true);
// create dialog and set content
JDialog dlg = new JDialog(parent, "Dialog", true);
dlg.setLocationRelativeTo(parent);
dlg.getContentPane().add(dlgContent);
dlg.pack();
dlg.setVisible(true);
}
}
Hope I could help you.

Related

How to set an action to occur whenever JFXPanel is closed?

I'm building a Swing application and I'm using JFXPanel to bring up a WebView for user authentication. I need to return the url that the WebEngine is sent to after a successful user sign-on- but I don't know how to pull the URL from the view at the time the window is closed. I'm aware of Stage.setOnHiding, but this can't apply here since JFXPanels don't act as stages, though they contain a scene.
I'm very new to JavaFX so if this code snippet demonstrates bad conventions, I'd be happy to hear it!
private static void buildAuthBrowser() {
JFrame frame = new JFrame("frame");
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);
frame.setSize(800, 600);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Platform.runLater(new Runnable() {
#Override
public void run() {
initFX(fxPanel);
}
});
}
private static void initFX(JFXPanel fxPanel) {
// fx thread
Scene scene = createScene();
fxPanel.setScene(scene);
}
private static Scene createScene() {
Group root = new Group();
Scene scene = new Scene(root);
WebView view = new WebView();
WebEngine browser = view.getEngine();
browser.load(auth.getUrl());
root.getChildren().add(view);
return (scene);
}
Found a solution- I was able to set a listener on the engine in the scene builder method, this way, every time the browser visits a new URL it automatically updates a private variable.
in createScene():
authBrowser.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> {
if (Worker.State.SUCCEEDED.equals(newValue)) {
setCode(authBrowser.getLocation());
}
});

How to prevent window to be clickable/do actions on it in javafx? [duplicate]

I can't figure out how to create a modal window in JavaFX. Basically I have file chooser and I want to ask the user a question when they select a file. I need this information in order to parse the file, so the execution needs to wait for the answer.
I've seen this question but I've not been able to find out how to implement this behavior.
In my opinion this is not good solution, because parent window is all time active.
For example if You want open window as modal after click button...
private void clickShow(ActionEvent event) {
Stage stage = new Stage();
Parent root = FXMLLoader.load(
YourClassController.class.getResource("YourClass.fxml"));
stage.setScene(new Scene(root));
stage.setTitle("My modal window");
stage.initModality(Modality.WINDOW_MODAL);
stage.initOwner(
((Node)event.getSource()).getScene().getWindow() );
stage.show();
}
Now Your new window is REALY modal - parent is block.
also You can use
Modality.APPLICATION_MODAL
Here is link to a solution I created earlier for modal dialogs in JavaFX 2.1
The solution creates a modal stage on top of the current stage and takes action on the dialog results via event handlers for the dialog controls.
JavaFX 8+
The prior linked solution uses a dated event handler approach to take action after a dialog was dismissed. That approach was valid for pre-JavaFX 2.2 implementations. For JavaFX 8+ there is no need for event handers, instead, use the new Stage showAndWait() method. For example:
Stage dialog = new Stage();
// populate dialog with controls.
...
dialog.initOwner(parentStage);
dialog.initModality(Modality.APPLICATION_MODAL);
dialog.showAndWait();
// process result of dialog operation.
...
Note that, in order for things to work as expected, it is important to initialize the owner of the Stage and to initialize the modality of the Stage to either WINDOW_MODAL or APPLICATION_MODAL.
There are some high quality standard UI dialogs in JavaFX 8 and ControlsFX, if they fit your requirements, I advise using those rather than developing your own. Those in-built JavaFX Dialog and Alert classes also have initOwner and initModality and showAndWait methods, so that you can set the modality for them as you wish (note that, by default, the in-built dialogs are application modal).
You can create application like my sample. This is only single file JavaFX application.
public class JavaFXApplication1 extends Application {
#Override
public void start(Stage primaryStage) {
Button btn = new Button();
btn.setText("Say 'Hello World'");
btn.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
Stage stage;
stage = new Stage();
final SwingNode swingNode = new SwingNode();
createSwingContent(swingNode);
StackPane pane = new StackPane();
pane.getChildren().add(swingNode);
stage.initModality(Modality.APPLICATION_MODAL);
stage.setTitle("Swing in JavaFX");
stage.setScene(new Scene(pane, 250, 150));
stage.show();
}
});
StackPane root = new StackPane();
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
private void createSwingContent(final SwingNode swingNode) {
SwingUtilities.invokeLater(() -> {
try {
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
JasperDesign jasperDesign = JRXmlLoader.load(s + "/src/reports/report1.jrxml");
String query = "SELECT * FROM `accounttype`";
JRDesignQuery jrquery = new JRDesignQuery();
jrquery.setText(query);
jasperDesign.setQuery(jrquery);
JasperReport jasperReport = JasperCompileManager.compileReport(jasperDesign);
JasperPrint JasperPrint = JasperFillManager.fillReport(jasperReport, null, c);
//JRViewer viewer = new JRViewer(JasperPrint);
swingNode.setContent(new JRViewer(JasperPrint));
} catch (JRException ex) {
Logger.getLogger(AccountTypeController.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

Creating new Transparent Stage on Event JavaFX

I'm trying to create a new Stage when a button is pressed.
It works but the problem is that I'd like this Stage to be fully transparent and lets us see what's behind the screen.
Code
Dimension Sizescreen = Toolkit.getDefaultToolkit().getScreenSize();
//Main stage with option menu
Pane window = new Pane();
Scene scene = new Scene(window);
stage.setTitle("Notification Extender");
//Create the button SetLooker
Button SetLooker = new Button("Set Looker");
//Add a Event when pressed
SetLooker.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent e) {
//Create a sub-Stage
Pane subwindow = new Pane();
Scene subscene = new Scene(subwindow);
Stage substage = new Stage();
substage.setTitle("Notification Extender");
//Set this subStage Transparent
substage.initStyle(StageStyle.TRANSPARENT);
subscene.setFill(Color.TRANSPARENT);
substage.setWidth(Sizescreen.getWidth());
substage.setHeight(Sizescreen.getHeight());
substage.setX(0);
substage.setY(0);
//Create a a graphique element
Rectangle redrec = new Rectangle(120,40,50,50);
redrec.setStroke(Color.RED);
redrec.setStrokeWidth(2);
redrec.setFill(Color.TRANSPARENT);
//Add the graphique element to the sub-stage
subwindow.getChildren().add(redrec);
//Show the sub-stage
substage.setScene(subscene);
substage.show();
}
});
//Add the button to the main stage
window.getChildren().add(SetLooker);
//Show the main stage
stage.setScene(scene);
stage.show();
The problem is that when I press the button it shows the stage but it's not transparent at all it's completely white.
I've also tried to change the main Stage, but I cannot change it once it has been shown.
You also need to remove the background from the root of your new scene:
subwindow.setBackground(null);

Add a JPanel in a BorderPane

I have a Java project that plays a .flv media file through JavaFX Media Player, and it's working fine. Recently, I've been wanting to experiment by adding GUI components to this Project (JPanel, JLabel). However, I've failed in all my attempts and after doing some research turns out it's not as simple as i first thought.. I've tried borderPane.setTop(JLabel) but I get a "Cannot convert Jlabel to Node" error.. I feel that I'm missing something
If anyone has any idea why this isnt working for me, I would greatly appreciate any form of explanation or examples.. :)
Here is the code if it might be of use to you!
#Override
public void start(Stage stage){
String path = "Data/Video/Clip.flv";
Media media = new Media(new File(path).toURI().toString());
MediaPlayer mediaPlayer = new MediaPlayer(media);
MediaView mediaView = new MediaView(mediaPlayer);
BorderPane borderPane = new BorderPane();
borderPane.setCenter(mediaView);
//borderPane.add(logoPanel); <<<<<<< Error
Scene scene = new Scene(borderPane, 1024, 800);
scene.setFill(javafx.scene.paint.Color.BLACK);
stage.setTitle("Media Player");
stage.setScene(scene);
stage.show();
mediaPlayer.setAutoPlay(true);
BorderPane is a JavaFX Node whereas JPanel is a Java Swing Component.
You cannot add a JPanel to a BorderPane, what you are looking for instead is the JavaFX equivalent of the JPanel which is the Pane class.
If you are developing using JavaFX it is easier to just use JavaFX components. If you must use Swing components then you can use the SwingNode class.
What you basically want to achieve: add some Swing components to an JavaFX application.
You have to use SwingNode class to "wrap" a JComponent.
SwingNode Class
JavaFX 8 introduces the SwingNode class, which is located in the
javafx.embed.swing package. This class enables you to embed Swing
content in a JavaFX application. To specify the content of the
SwingNode object, call the setContent method, which accepts an
instance of the javax.swing.JComponent class.
You can check this tutorial how embed Swing component into JavaFX application.
Small example to put a Swing Button into the center of a BorderPane:
public class Main extends Application {
#Override
public void start(Stage primaryStage) {
try {
BorderPane root = new BorderPane();
Scene scene = new Scene(root,400,400);
SwingNode swingNode = new SwingNode();
JButton jButton = new JButton("I am a Swing button");
jButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
System.out.println("Message from Swing");
}
});
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
swingNode.setContent(jButton);
}
});
root.setCenter(swingNode);
primaryStage.setScene(scene);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}
}
By the way, BorderPane has no method "add" (as in your commented line):
You can use setCenter, setTop, setBottom, setLeft and setRight to add Nodes into it (as you used to fill the center).
If your goal was not to embed Swing into JavaFX, just to use JavaFX controls, you can check this article what controls JavaFX has by default.

JavaFX Modal Window ownership to Swing

I have an application built on Swing integrated with JavaFX. Swing's JFrame is the top-level window, with JFXPanel housing different JavaFX controls. Now, I am also integrating JavaFX's new Alert API, and currently having difficulty in setting Alert's ownership when shown. That is, I would like to make JFrame as the owner of Alert.
JFXPanel fxPanel = new JFXPanel();
Platform.runLater(() -> {
Button button = new Button("Alert");
button.setOnAction(evt -> {
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setHeaderText("An Alert");
alert.setContentText("Alerting");
alert.initModality(Modality.APPLICATION_MODAL);
alert.initOwner(button.getScene().getWindow());
alert.initStyle(StageStyle.UTILITY);
alert.show();
});
BorderPane borderPane = new BorderPane();
borderPane.setCenter(button);
Scene scene = new Scene(borderPane, 300, 300);
SwingUtilities.invokeLater(() -> {
fxPanel.setScene(scene);
JFrame frame = new JFrame("App");
frame.add(fxPanel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
});
});
I understand that when a window reference is taken in this code alert.initOwner(button.getScene().getWindow());, com.sun.javafx.stage.EmbeddedWindow object is returned. I know that it would be impossible to take JFrame as the window owner of Alert. But, is there a hack to make this happen?
Look here:
http://docs.oracle.com/javase/8/javafx/interoperability-tutorial/swing-fx-interoperability.htm
It says something like this ->
JFrame frame = new JFrame("Swing and JavaFX");
final JFXPanel fxPanel = new JFXPanel();
frame.add(fxPanel);

Categories

Resources