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()
);
Related
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();
}
So, for my class project I am making a game. I want to add a volume slider to change the music volume. I am very stuck here. Please help me.
I was following tutorial, and I was able to display it on the scree. But, the volume doesn't change, even though I slide the bar. Can somebody give me advice? Thank you.
private Scene createOptionScene() {
String path = "E:\\All Computer Science Materials\\Java 240 Project\\PrinceFX\\Music\\"
+ songs.getSong(1) + ".mp3";
Media media = new Media(new File(path).toURI().toString());
currentPlay = new AudioClip(media.getSource());
currentPlay.setCycleCount(MediaPlayer.INDEFINITE);
currentPlay.play();
// Volume Control
volumeSlider.setValue(currentPlay.getVolume() * 100);
volumeSlider.valueProperty().addListener(new InvalidationListener() {
#Override
public void invalidated(Observable observable) {
currentPlay.setVolume(volumeSlider.getValue() / 100);
}
});
HBox temp = new HBox();
temp.getChildren().addAll(volumeSlider);
temp.setTranslateX(850);
temp.setTranslateY(410);
volumeSlider.setMinWidth(300);
Image image = new Image(new File("E:\\All Computer Science Materials\\" +
"Java 240 Project\\PrinceFX\\image\\" + picture.getImage(2) + ".png").toURI().toString());
//Setting the image view
ImageView imageView = new ImageView(image);
//Setting the position of the image
imageView.setX(0);
imageView.setY(0);
//setting the fit height and width of the image view
imageView.setFitHeight(primaryScreenBounds.getHeight());
imageView.setFitWidth(primaryScreenBounds.getWidth());
//Setting the preserve ratio of the image view
imageView.setPreserveRatio(true);
Label labelOption = new Label();
Button goBack = new Button("Go Back to Main");
goBack.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
currentPlay.stop();
sceneStart = createStartScene();
stageOne.setScene(sceneStart);
}
});
// Button to the main page.
HBox layoutOp = new HBox(15);
layoutOp.getChildren().addAll(labelOption, goBack);
// Button coordinate.
layoutOp.setTranslateX(1400);
layoutOp.setTranslateY(750);
Group gOption = new Group(imageView, layoutOp, temp);
return new Scene(gOption, 200, 200);
}
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
I am trying to switch to javafx instead of swing but it has been a bit bumpy trying to find methods that do the exact tasks.
I am trying to get the buttons width to fill the entire scene and adjusts accordingly when you adjust the scene size.
Get a small empty border around text area and buttons.
Getting a method that reads a plain text file and replaces the current Text Area (not append).
package gui;
mport javafx.application.Application;
mport javafx.scene.Scene;
mport javafx.scene.control.Button;
mport javafx.stage.Stage;
mport javafx.scene.layout.*;
mport javafx.scene.control.TextArea;
public class Main extends Application{
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("TextArea Experiment 1");
TextArea textArea = new TextArea();
// Which TextArea method would I call to set a plain
// text file into the text area ?
BorderPane border = new BorderPane();
border.setCenter(textArea);
//border.setBorder(new EmptyBorder(10,10,10,10));
// Is there a method like this in JavaFx ?
GridPane grid = new GridPane();
border.setBottom(grid);
double screensize = border.getMaxWidth();
Button option1 = new Button("Button 1");
Button option2 = new Button("Button 2");
Button option3 = new Button("Button 3");
// how can I get the buttons to be max scene size and
//adjust dynamically to scene dimensions ?
option1.setMaxSize(Double.MAX_VALUE,Double.MAX_VALUE);
//option1.setPrefWidth(Double.MAX_VALUE);
System.out.println(screensize);
grid.add(option1, 0,1);
grid.add(option2,0,2);
grid.add(option3,0,3);
Scene scene = new Scene(border, 200, 100);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
Application.launch(args);
}
}
first of all I suggest that to take a look at this tutorial: http://code.makery.ch/library/javafx-8-tutorial/
If you want to build a well structured javafx application you have to make an .fxml file, a Controller class and (some) model class(es).
But for those points here are the answers.
If you want to set a Region's size you have to use .setPrefSize(double,double) method, if you want to set dynamic you have to use for example myButton.prefSizeProperty().bind(anyRegionYouWantToBindTo.widthProprty())
I don't really understand what you want, I think you would like to use some styling, then you can write a .css file then arr it to textArea's styleClass.
After you get the text from the file instead of using textArea.appendText(String) you have to user textArea.setText(String)
I think these are the sollutions for your problems but I strongly recommend to read a tutorial about javafx. So have fun :)
Rewrite your question and only ask the question for this answer. You can then ask the other questions on their own thread.
GridPane grid = new GridPane();
grid.setMaxWidth(Double.MAX_VALUE);//Make sure the GridPane MaxWidth is set to MAX_VALUE. you can use grid.gridLinesVisibleProperty().set(true); to get an idea of the GRIDPANES current borders
border.setBottom(grid);
grid.gridLinesVisibleProperty().set(true);
Button option1 = new Button("Button 1");
option1.setMaxWidth(Double.MAX_VALUE);//Set button one MaxWidth to MAX_VALUE
Button option2 = new Button("Button 2");
option2.setMaxWidth(Double.MAX_VALUE);//Set button two MaxWidth to MAX_VALUE
Button option3 = new Button("Button 3");
option3.setMaxWidth(Double.MAX_VALUE);//Set button three MaxWidth to MAX_VALUE
//Add ColumnConstraints and set the width to 100%.
ColumnConstraints columnConstraint = new ColumnConstraints();
columnConstraint.setPercentWidth(100);
grid.getColumnConstraints().add(0, columnConstraint);
grid.add(option1, 0, 1);
grid.add(option2, 0, 2);
grid.add(option3, 0, 3);
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);
}
}