Pause issue JavaFX - javafx

I'm trying to build a media player with JavaFX. First, I loaded a video, next I created pause button and work fine. When i load a new video with the open button ("apri") the video works but the pause button won't work properly -_- here my main class.. I don'have used the scenebuilder but I'm trying with only the code
public class Main extends Application {
public String indirizzo = "file:///C:/Users/ASUS/Desktop/film/prova1.mp4";
#Override
public void start(Stage primaryStage) {
try {
/* Creo la scena e mi faccio passare il media da visualizzare */
/* Creo i pannelli */
BorderPane bp = new BorderPane();
StackPane sp = new StackPane();
HBox hb = new HBox(5);
VBox vb = new VBox();
/* Primo video */
MediaView mv = new MediaView();
Media m = new Media(indirizzo);
MediaPlayer mp = new MediaPlayer(m);
mv.setMediaPlayer(mp);
mp.play();
/* Creo gli oggetti nella parte bassa*/
Slider misc = new Slider();
Slider sl = new Slider();
Label volume = new Label("Volume: ");
Button btn1 = new Button("Apri");
Button btn2 = new Button("<<");
Button btn3 = new Button("| |");
Button btn4 = new Button(">>");
hb.setAlignment(Pos.CENTER);
hb.setPadding(new Insets(5,10,5,10));
/* Dimensioni slider */
sl.setPrefWidth(70);
sl.setMinWidth(30);
sl.setValue(100);
/* Posiziono i pannelli */
bp.setCenter(mv);
hb.getChildren().addAll(btn1,btn2,btn3,btn4,volume,sl);
vb.getChildren().addAll(misc,hb);
bp.setBottom(vb);
/* Se schiaccio il pulsante apri */
btn1.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
/* Prima metto in pausa il video */
FileChooser fc = new FileChooser();
ExtensionFilter filtro = new ExtensionFilter("Seleziona media (*.mp4)","*.mp4");
fc.getExtensionFilters().add(filtro);
/* Apro la finestra di dialogo per caricare il file */
File file = fc.showOpenDialog(null);
indirizzo = file.toURI().toString();
if(file != null){
/* Carico il media nel mp */
Media m = new Media(indirizzo);
MediaPlayer mp = new MediaPlayer(m);
mv.setMediaPlayer(mp);
/* Imposto dimensione Media View*/
mv.setFitHeight(500); /* Vanno bindate con la scene*/
mv.setFitWidth(500);
mp.play();
DoubleProperty mvw = mv.fitWidthProperty();
DoubleProperty mvh = mv.fitHeightProperty();
mvw.bind(Bindings.selectDouble(mv.sceneProperty(), "width"));
mvh.bind(Bindings.selectDouble(mv.sceneProperty(), "height"));
mv.setPreserveRatio(true);
}
}
});
btn3.setOnAction((ActionEvent e) -> {
Status currentStatus = mp.getStatus();
if(currentStatus == Status.PLAYING)
mp.pause();
else if(currentStatus == Status.PAUSED || currentStatus == Status.STOPPED){
mp.play();
}
});
Scene scena = new Scene(bp,500,500);
scena.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scena);
primaryStage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
launch(args);
}

Here is the problem:
if(file != null){
/* Carico il media nel mp */
Media m = new Media(indirizzo);
MediaPlayer mp = new MediaPlayer(m);
You are using new variable mp which is not visible to btn3.setOnAction() handler.
To address that make MediaPlayer mp a class' field and don't introduce new variables with the mp name.

Related

How do I make my buttons all the same size?

Sorry, I have just begun learning javaFX and cannot figure out how to get all of my icons on buttons the same size. I tried a couple things but could not get it working, all help is appreciated. Thank you!
Wont let me post my question unless I add more details but I cant think of anything else to put so just ignore this whole paragraph as I ramble on so I can post my question and continue coding my game.
public class Main extends Application {
Stage window;
Button button;
Scene scene1, scene2;
public static final int ROCK = 0;
public static final int PAPER = 1;
public static final int SCISSORS = 2;
public static int userChoice;
public static void main(String [] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception
{
window = primaryStage;
//Layout 1
VBox layout = new VBox(20);
Label label = new Label("Rock Paper Scissors");
Button myButton = new Button("Start");
myButton.setOnAction(e -> window.setScene(scene2));
Button exit = new Button("Exit");
exit.setOnAction(e -> System.exit(0));
layout.getChildren().addAll(label, myButton, exit);
layout.setAlignment(Pos.CENTER);
scene1 = new Scene(layout, 300, 300);
//Layout 2
BorderPane border = new BorderPane();
VBox layout1 = new VBox(10);
Label label1 = new Label("Choose One");
layout1.setAlignment(Pos.CENTER);
//Layout 3
HBox layout2 = new HBox(10);
//Rock Image Button
Image rockIm = new Image(getClass().getResourceAsStream("Rock2.png"));
Button rock = new Button();
rock.setGraphic(new ImageView(rockIm));
rock.setOnAction(e -> userChoice = ROCK);
//Paper Image Button
Image paperIm = new
Image(getClass().getResourceAsStream("Paper2.png"));
Button paper = new Button();
paper.setGraphic(new ImageView(paperIm));
paper.setOnAction(e -> userChoice = PAPER);
//Scissor Image Button
Image scissorIm = new
Image(getClass().getResourceAsStream("Scissor2.png"));
Button scissors = new Button();
scissors.setGraphic(new ImageView(scissorIm));
scissors.setOnAction(e -> userChoice = SCISSORS);
Button quit = new Button("Return");
quit.setOnAction(e -> window.setScene(scene1));
layout2.getChildren().addAll(rock, paper, scissors, quit);
layout2.setAlignment(Pos.CENTER);
scene2 = new Scene(layout2, 300, 300);
window.setTitle("Rock Paper Scissors");
window.setScene(scene1);
window.show();
}
}

Pair<String, Runnable> in a game menu

I'm trying to create a game Menu using javafx. I have now the front page that works. I have a couple of items that should lead me to the next scenes.
I use :
private List<Pair<String, Runnable>> menuData = Arrays.asList(
new Pair<String, Runnable>("Un Joueur", OptionMenu::),
new Pair<String, Runnable>("Multijoueuer", () -> {}),
new Pair<String, Runnable>("Options du jeu", () -> {}),
new Pair<String, Runnable>("Quitter",Platform::exit)
);
to create my items and Platform::exit to quite everything.
The question is: How can I create a Runnable like my OptionMenu::something that leads me to my next page that extends Application. I would like it to be close to that :
public abstract static class OptionMenu extends Application implements Runnable{
///////// définition de la taille du menu ///////////
private static final int WIDTH = 1324;
private static final int HEIGHT = 604;
/////////////////////////////////////////////////////
//////// création des differents clicables //////////
private List<Pair<String, Runnable>> menuData = Arrays.asList(
new Pair<String, Runnable>("Un Joueur", () -> {}),
new Pair<String, Runnable>("Multijoueuer", () -> {}),
new Pair<String, Runnable>("Options du jeu", () -> {}),
new Pair<String, Runnable>("Quitter",Platform::exit)
);
//////////////////////////////////////////////////////
private Pane root = new Pane();
private VBox menuBox = new VBox(-5);
private void addBackground(){
ImageView imageView = new ImageView(new Image(getClass().getResource("MenuImages/bkground.jpg").toExternalForm()));
imageView.setFitWidth(WIDTH);
imageView.setFitHeight(HEIGHT);
root.getChildren().add(imageView);
}
private void addTitle() {
BomberBallTitle title = new BomberBallTitle("Options du jeu");
title.setTranslateX(WIDTH / 2 - title.getTitleWidth() / 2);
title.setTranslateY(HEIGHT / 3);
root.getChildren().add(title);
}
private void addMenu(double x, double y) {
menuBox.setTranslateX(x);
menuBox.setTranslateY(y);
menuData.forEach(data -> {
BomberBallMenuItem item = new BomberBallMenuItem(data.getKey());
item.setOnAction(data.getValue());
item.setTranslateX(-300);
Rectangle clip = new Rectangle(300, 30);
clip.translateXProperty().bind(item.translateXProperty().negate());
item.setClip(clip);
menuBox.getChildren().addAll(item);
});
root.getChildren().add(menuBox);
}
private Parent createContent() {
addBackground();
addTitle();
double lineX = WIDTH / 2 - 100;
double lineY = HEIGHT / 3 + 50;
addMenu(lineX + 5, lineY + 5);
return root;
}
public void run() {
launch();
}
#Override
public void start(Stage primaryStage) throws Exception{
Scene scene = new Scene(createContent());
primaryStage.setTitle("BomberBall Menu");
primaryStage.setScene(scene);
primaryStage.show();
}

javafx stagestyle UNDECORATED

I'm using a translator.
enter image description here
Windows desktop appears unexpectedly when you click on the image.
Scrollpane -> BorderPane
Normal at first Occurs like an image later
FXMLLoader loader = new FXMLLoader(getClass().getResource("/View/Main_fx.fxml"));
Parent root = loader.load();
st = new Stage();
final UndecoratorScene undecorator = new UndecoratorScene(st, (Region) root);//NewMainScene lib 사용(프로젝트 및 패키지 명 :Newtable)
undecorator.getStylesheets().add(getClass().getResource("/View/winDec.css").toExternalForm());
st.setScene(undecorator);
stage = (Stage) lb.getScene().getWindow();
st.getIcons().add(new Image(config2.class.getResourceAsStream("/View/207411.jpg" )));
st.initStyle(StageStyle.TRANSPARENT); //스타일 미적용.
st.setResizable(resize);
st.setMaximized(maximized);
st.setTitle(judul);
st.sizeToScene();
// Undecorator undecor = undecorator.getUndecorator();
//최소로 줄이수 있는 화면 크기 값 .
st.setMinWidth(350);
st.setMinHeight(200);
GetStage gs = new GetStage();//트레이 창으로 보낼때 현재 Stage 값 전달.
gs.SetStage(st);
st.toFront();
st.show();
Rectangle2D primScreenBounds = Screen.getPrimary().getVisualBounds();
st.setX((primScreenBounds.getWidth() - st.getWidth()) / 2);
st.setY((primScreenBounds.getHeight() - st.getHeight()) / 2);
createTrayIcon(st);//트레이 창 이벤트 메소드
firstTime = true;
Platform.setImplicitExit(false);
stage.close();//controllSplash stage 종료
Hander_Main controller = (Hander_Main)loader.getController();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
Date sys_date = new Date();
String now= formatter.format(sys_date);
controller.setPrimaryStage(st);
controller.setScene(undecorator);
controller.setFirstDate(now);
st.setOnCloseRequest(new EventHandler<WindowEvent>() {
public void handle(WindowEvent we)
{
hide(st);
}
});
} catch (Exception e) {
st.hide();
dialog(Alert.AlertType.ERROR,"Main_fx Stage ERR\n"+e);
System.exit(0);
}

why javafx mediaplayer status sometimes returns unknown?

First i am sorry for my poor english...
i made Media Player Application with Javafx.
this player can get mulit file media. and play files out of all limits.
it work well. but sometimes not work..
it is not media error. it is mediaplayer error.
error message is 'mediaPlayer Unknown, media Invalid..' why.??
i played same video file(1920 * 1080), sometimes work and sometimes not work..
and javafx is depend on OS ??
player works perfectly on windown7 computer
but player have this error on windown10 computer...
please give me advice..
MediaPlayer mediaPlayer = null;
Stage stage = new Stage();
AnchorPane pane = new AnchorPane();
Scene scene = new Scene(pane);
MediaView mediaView = new MediaView();
int mNextFileIndex = -1;
List<File> fileLists = new ArrayList<>();
Media media;
mediaplayer play Method
public void playNextMedia() {
if (mediaPlayer != null) {
mediaPlayer.dispose();
mediaView.setMediaPlayer(null);
}
mNextFileIndex = (mNextFileIndex + 1) % fileLists.size();
media =new Media(fileLists.get(mNextFileIndex).toURI().toString());
media.setOnError(()-> {
MainApp.makeLog("media error");
});
mediaPlayer = new MediaPlayer(media);
mediaView.setMediaPlayer(mediaPlayer);
mediaPlayer.setOnReady(() -> {
mediaPlayer.play();
});
mediaPlayer.setOnEndOfMedia(() -> {
playNextMedia();
});
mediaPlayer.setOnError(() -> {
systom.out.println("mediaPlayer error");
Systeom.out.println(mediaPlayer.getError().getMessage());
playNextMedia();
});
}
Button Method
#FXML
private void playMedia(ActionEvent event) {
mNextFileIndex = -1;
FileChooser fileChooser = new FileChooser();
fileChooser.getExtensionFilters().addAll(new
FileChooser.ExtensionFilter("Select a File (*.mp4)", "*.mp4"),
new FileChooser.ExtensionFilter("All Files", "*.*"));
List<File> list = fileChooser.showOpenMultipleDialog(null);
if (list != null) {
for (File file : list) {
fileLists.add(file)
}
playNextMedia();
pane.getChildren().add(mediaView);
stage.setScene(scene);
stage.show();
}

How to get data from Tab in Tabpane JavaFX

I want get data from Tab in Tabpane JavaFX
I have 2 Tab in Tabpane, And each Tab I have a TextArea, I want click Button will get data from 2 tab
Here's my code:
btnThem.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
try {
i++;
FXMLLoader fxmlLoader = new FXMLLoader(
getClass().getResource("/fxml/tab.fxml"));
Parent parent = (Parent) fxmlLoader.load();
Tab tab = new Tab("Điểm " + i);
tab.setContent(parent);
tab.setClosable(true);
tabPane.getTabs().add(tab);
controllerTab = (ControllerTab) fxmlLoader.getController();
} catch (IOException ex) {
Exceptions.printStackTrace(ex);
}
}
});
Your question is ambiguous but it seems you want to get data from each textArea in tab.To do this you should get nodes (children) from each tab and by using lookup() we confirm and we parse node to textArea.I tried to figure your scene and made this example to help you :
public class example extends Application {
TextArea textArea = new TextArea();
TextArea textArea1 = new TextArea();
Button button = new Button("button");
#Override
public void start(Stage primaryStage) {
Tab tab1 = new Tab("tab1");
Tab tab2 = new Tab("tab2");
tab1.setContent(textArea);
tab2.setContent(textArea1);
TabPane pane = new TabPane();
pane.getTabs().addAll(tab1, tab2);
Node node1 = tab1.getContent();
Node node2 = tab2.getContent();
button.setOnAction((ActionEvent event) -> {
if (node1.lookup("TextArea") != null && node2.lookup("TextArea") != null) {
TextArea area1 = (TextArea) node1.lookup("TextArea");
TextArea area2 = (TextArea) node2.lookup("TextArea");
System.out.println(area1.getText() + " " + area2.getText());
}
});
VBox root = new VBox();
root.setAlignment(Pos.TOP_RIGHT);
root.getChildren().add(pane);
root.getChildren().add(button);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}
And you can see the result :
Hello ,tab1 Hello ,tab2
Deleting directory C:\Users\Electron\Documents\NetBeansProjects\Buttono\dist\run341573612
jfxsa-run:
BUILD SUCCESSFUL (total time: 22 seconds)

Resources