I have this window here:
JFrame rainbow = new JFrame();
rainbow.setSize(new Dimension(500, 500));
rainbow.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
rainbow.setTitle("RaInBoW");
rainbow.setResizable(false);
rainbow.setLocationRelativeTo(null);
Media rainbowMusic = new Media("file:///C:/Users/Julius/Downloads/rainbowMusic.mp3");
MediaPlayer mediaPlayer = new MediaPlayer(rainbowMusic);
mediaPlayer.setAutoPlay(true);
rainbow.setLayout(new GridLayout(1, 1, 0, 0));
Draw d = new Draw();
rainbow.add(d);
rainbow.setVisible(true);
Is there a way to stop the MediaPlayer from playing music after closing the JFrame? If yes, could you please tell me?
Add a close listener to your JFrame like so
rainbow.addWindowListener(new WindowAdapter()
{
// runs whenever the user tries to close the fram
#Override
public void windowClosing(WindowEvent e)
{
mediaPlayer.pause();
}
});
This will pause the media player whenever the frame is closed
Related
I am building a game engine as a school project. When I add button to the same group as where I have my canvas, I can't control my player anymore with keyboard. Buttons and everything else still works like normal.
My code is pretty huge, so this is a simplified code of the problem:
public abstract class GEngine extends Application {
public void start(Stage theStage) throws Exception {
try {
this.stage = theStage;
Group root = new Group();
Scene theScene = new Scene(root);
stage.setScene(theScene);
Canvas canvas = new Canvas(windowWidth, windowHeight);
root.getChildren().add(canvas);
Button btn = new Button("new");
btn.setOnMousePressed(e->System.out.println("press"));
root.getChildren().add(btn);
Timeline gameLoop = new Timeline();
gameLoop.setCycleCount(Timeline.INDEFINITE);
// Handle input
theScene.setOnKeyPressed(Input::handlePressed);
theScene.setOnKeyReleased(Input::handleReleased);
// Control game loop and it's speed
KeyFrame kf = new KeyFrame(
Duration.seconds(0.017), // 60 FPS
(e)->this.controlGameLoop());
gameLoop.getKeyFrames().add( kf );
gameLoop.play();
stage.show();
} catch (Exception e) {
e.printStackTrace();
stop();
}
}
}
There is probably something happening on the background which I just don't understand. I can show my Input class code too if somebody wants to see it, but in my understanding it's not necessary.
I have tried using AnchorPane as main root and make a separate groups for buttons and canvas which I add the to the AnchorPane, but that did not help at all. That was pretty much the only offered solution I could find from google.
Adding btn.setFocusTraversable(false); fixed the problem, thanks to Luxusproblem for providing the answer!
We created a Custom Dialog without an FXML file. We are using JavaFX 8.
The dialog loads and functions as expected but we can not move the Buttons and the TextField to enhance the styling.
We have tried to use tf.setLayoutY(50) this has no effect.
We used this tf.setPromptText("This Works ?") and it works.
We would rather not use css to accomplish this styling.
And we will consider a FXML file if we can keep the two event handlers that force data to be entered in the TextField.
So the question is: How to style this Custom Dialog?
The code is a mess as it includes some concepts we tried:
public void CustomDialog() {
Dialog dialog = new Dialog<>();
dialog.setResizable(false);
final Window window = dialog.getDialogPane().getScene().getWindow();
stage = (Stage) window;
stage.setMinHeight(600);
stage.setMinWidth(400);
TextField tf = new TextField();
tf.setLayoutX(10);
tf.setLayoutY(50);
dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);
dialog.getDialogPane().getChildren().add(tf);
dialog.getDialogPane().setContent(tf);
// Create an event filter that consumes the action if the text is empty
EventHandler<ActionEvent> filter = event -> {
if (tf.getText().isEmpty()) {
event.consume();
}
};
// lookup the buttons
ButtonBase okButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.OK);
Button cancelButton = (Button) dialog.getDialogPane().lookupButton(ButtonType.CANCEL);
// add the event-filter
okButton.addEventFilter(ActionEvent.ACTION, filter);
cancelButton.addEventFilter(ActionEvent.ACTION, filter);
stage.setOnCloseRequest(event -> {
if (tf.getText().isEmpty()) {
event.consume();
}
}
//Scene scene = new Scene(root);
//dialogStage.setScene(scene);
dialog.initModality(Modality.APPLICATION_MODAL);
//dialogStage.setAlwaysOnTop(true);
//dialogStage.setResizable(false);
tf.setPromptText("This Works ?");
tf.requestFocus();// This does not work
dialog.showAndWait();
}
Grendel we enhanced your answer so anyone who comes by and sees the code you posted in your question will understand as you said it was a mess
Your posted answer was real old school but less work perhaps than building a FXML file
Besides it is good to know some old school tricks
public void NewDialog(){
Label lblAmt = new Label("Enter Amount");
Button btnOK = new Button("OK");
TextField txtAmt = new TextField();
AnchorPane secondaryLayout = new AnchorPane();
secondaryLayout.setStyle("-fx-border-color:red;-fx-border-width:10px; -fx-background-color: lightblue;");
secondaryLayout.getChildren().addAll(lblAmt,btnOK,txtAmt);
lblAmt.setLayoutX(30);
lblAmt.setLayoutY(30);
txtAmt.setLayoutX(164);
txtAmt.setLayoutY(25);
txtAmt.setMaxWidth(116);
btnOK.setLayoutX(190);
btnOK.setLayoutY(100);
btnOK.setStyle("-fx-font-size: 18px;-fx-font-weight: bold;");
lblAmt.setStyle("-fx-font-size: 18px;-fx-font-weight: bold;");
txtAmt.setStyle("-fx-font-size: 18px;-fx-font-weight: bold;");
Scene secondScene = new Scene(secondaryLayout, 300, 180);
EventHandler<ActionEvent> filter = event -> {
if(txtAmt.getText().isEmpty()) {
event.consume();
}
};
// New window (Stage)
Stage newWindow = new Stage();
newWindow.initStyle(StageStyle.UNDECORATED);
//newWindow.initModality(Modality.APPLICATION_MODAL);
newWindow.setResizable(false);
newWindow.setTitle("Second Stage");
newWindow.setScene(secondScene);
btnOK.addEventHandler(ActionEvent.ACTION,filter);
btnOK.setOnAction(evt -> {
String str = txtAmt.getText();
System.out.println("################ str "+str);
if(txtAmt.getText().equals("")) {
evt.consume();
txtAmt.requestFocus();
}else{
newWindow.close();
}
});
newWindow.setOnCloseRequest(event -> {
if(txtAmt.getText().isEmpty()) {
event.consume();
}
});
txtAmt.requestFocus();
newWindow.showAndWait();
}
This question already has answers here:
Java FX 2 Alert sound
(4 answers)
Closed 6 years ago.
How can I add a sound notification when a window pops up? I want to add my custom sound file, not the windows sound.
Code:
public class PopupWindow {
Rectangle2D primaryScreenBounds = Screen.getPrimary().getVisualBounds();
public void display(String newCase) throws IOException {
Stage window = new Stage();
Image applicationIcon = new Image(getClass().getResourceAsStream("../images/logo.jpg"));
window.getIcons().add(applicationIcon);
window.initStyle(StageStyle.UNDECORATED);
Label txtNotification = new Label("Новых заявок:");
Label notification = new Label(newCase);
notification.setTranslateX(120);
notification.setStyle("-fx-text-fill: crimson");
Button closeButton = new Button("x");
closeButton.setTranslateX(205);
closeButton.setTranslateY(5);
closeButton.setOnAction(event -> window.close());
Pane layout = new Pane();
layout.getChildren().addAll(txtNotification, notification, closeButton);
window.setX(primaryScreenBounds.getMinX() + primaryScreenBounds.getWidth() - 245);
window.setY(primaryScreenBounds.getMinY() + primaryScreenBounds.getHeight() / 1.2);
Scene scene = new Scene(layout);
window.setScene(scene);
layout.getStylesheets().add(this.getClass().getResource("../style/popup.css").toExternalForm());
window.setAlwaysOnTop(true);
window.showAndWait();
}
}
Play an AudioClip, just before you call showAndWait() on your pop-up window:
AudioClip plonkSound = new AudioClip("http://somehost/path/plonk.aiff");
plonkSound.play();
If you want to load the audio clip from your class path (e.g. from your jar file in a sibling location to your PopopWindow.class), then get the clip as a resource:
AudioClip plonkSound = new AudioClip(
PopupWindow.getResource("plonk.aiff").toExternalForm()
);
I want to bring a fade effect when a new window appears. Also nothing should be possible without closing the window. My code to open the new window when a button is pressed in given below :
Button b4 = new Button("ABOUT");
b4.setFont(Font.font("Calibri", FontWeight.BOLD, 17));
b4.setPrefSize(100, 30);
b4.setStyle(" -fx-base: #ffffff;");
b4.setTextFill(Color.BLACK);
b4.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
Stage usrpagestage = new Stage();
usrpagestage.setMaxHeight(160);
usrpagestage.setMaxWidth(210);
usrpagestage.setResizable(false);
usrpagestage.initStyle(StageStyle.UTILITY);
usrpagestage.setScene(new Scene(new About()));
usrpagestage.show();
}
});
The current look of my 2 windows is given below. I only want to make visible the small window and the rest should appear as faded. How can I do it ?
try this..
b4.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent e) {
//Before open a add effect here
anchpane.setEffect(new BoxBlur(5, 10, 10)); // anchpane is anchor pane of main stage. change values of efect according your need. you can use any kind of pane of scene.
Stage usrpagestage = new Stage();
usrpagestage.setMaxHeight(160);
usrpagestage.setMaxWidth(210);
usrpagestage.setResizable(false);
usrpagestage.initStyle(StageStyle.UTILITY);
usrpagestage.setScene(new Scene(new About()));
usrpagestage.show();
}
});
Look like :
When you close the stage set it to default.
usrpagestage.setOnCloseRequest(new EventHandler<WindowEvent>() {
#Override
public void handle(WindowEvent t) {
anchpane.setEffect(new BoxBlur(0, 0, 0));
}
});
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);
}
}