ToogleButton with MediaView. JavaFX/Java - java

I'm trying to make an imitation of TV screen using java, javaFX and scenebulider. Right now I'm able to play the video but I don't know how to make it off at first, then after a button press it's going to play.
Here's my Controller code
public class Controller implements Initializable {
#FXML
private Slider suwak2;
#FXML
private Slider suwak5;
#FXML
private Slider suwak1;
#FXML
private Slider suwak4;
#FXML
private Slider suwak6;
#FXML
private Slider suwak3;
#FXML
private ToggleButton wlacznik;
#FXML
private MediaView mv;
private MediaPlayer mp;
private Media me;
#Override
public void initialize(URL location, ResourceBundle resources)
{
String path=new File("src/application/lol.mp4").getAbsolutePath();
Path clip = new Path(new MoveTo(50, 400), new ArcTo(50, 200, 0, 50, 0, false, true), new HLineTo(450), new ArcTo(50, 200, 0, 350, 400, false, true), new ClosePath());
clip.setFill(Color.BLACK);
clip.setStroke(null);
mv.setClip(clip);
me = new Media(new File(path).toURI().toString());
mp = new MediaPlayer(me);
mv.setMediaPlayer(mp);
mp.setAutoPlay(true);
mp.setCycleCount(MediaPlayer.INDEFINITE);
suwak1.setValue(mp.getVolume() * 100);
suwak1.valueProperty().addListener(new InvalidationListener() {
#Override
public void invalidated(Observable observable) {
mp.setVolume(suwak1.getValue()/100);
}
});
}
}
suwak1 is my volume slider, wlacznik is my toogle button to make it on and off.

Maybe you need a Button for Play/Stop
Button stop = new Button("STOP");
stop.setOnAction((e) -> mp.stop());
Button play = new Button("Play");
play.setOnAction((e) -> mp.play());

Related

Not able to click on Button JavaFX

I am creating a simple JavaFX based game and when I add a Button to my Pane and try to perform some action on it by clicking the mouse button while hovering over the button nothing happens - as if it is disabled but still visible.
private class Game extends Parent {
public Game() {
private Button newGameButton;
private Scene secondScene;
private Stage secondStage;
private Pane pane;
VBox menu = new VBox(15);
VBox highScore = new VBox(15);
menu.setTranslateX(280);
menu.setTranslateY(250);
highScore.setTranslateX(100);
highScore.setTranslateY(200);
try {
onLoad();
} catch (IOException e) {
e.printStackTrace();
}
newGameButton = new MenuButtonView("New Game");
newGameButton.setOnMouseClicked(event -> {
pane = new Pane();
secondScene = new Scene(pane, 800, 600);
secondStage = new Stage();
secondStage.setScene(secondScene);
secondStage.show();
scoreAndCrackView();
mickeyView();
});
public void mickeyView(){
private Button leftDownRedButton;
leftDownRedButton = new Button();
rightDownRedButton.setTranslateX(640);
rightDownRedButton.setTranslateY(560);
pane.getChildren().add(rightDownRedButton);
leftDownRedButton.setOnAction(new EventHandler<ActionEvent>() {
#Override public void handle(ActionEvent e) {
System.out.println("Clicked");
}
});
public void scoreAndCrackView()
{
vertBox = new VBox();
vertBox.setPrefSize(800, 100); // this one was causing issue, previously: vertBox.setPrefSize(800, 600)
vertBox.getChildren().addAll(scoreLabel,crackLabel);
pane.getChildren().add(vertBox);
}
}
UPDATE
Btw I found the cause of the error - as you guys suggested something was covering my buttons and more precisely the VBox in another method which was set to the whole screen. After changing the values and minimizing prefWidth and prefHeight I can click on the buttons. Lesson for the future to set the Box only for the required area.

If I wanted to resize a ImageView in JavaFX to only fit the entire left region of the borderpane without it resizing into the other regions?

I wanted to resize an image so it fits into the entire left region of a borderpane, but I don't understand the different regions of a borderpane. Do they all have the same dimensions? The code below I added a pane to the left region but I honestly don't really understand the automatic resizing of the regions depending of the size of the nodes added to it. Some pointers in the right direction would be nice. Also, this controller class is used to add a slideshow of images that fade in and fade out on a timer.
public class Controller implements Initializable {
#FXML public ImageView current;
public ImageView next;
#FXML public BorderPane borderPane;
#FXML public Button nextButton = new Button();
static int count = 0;
#FXML public Pane pane;
ArrayList<Image> imagesArrayList = new ArrayList<>();
#Override
public void initialize(URL url, ResourceBundle resourceBundle) {
imagesArrayList.add(new Image("/sample/pictures/download.jpg"));
imagesArrayList.add(new Image("/sample/pictures/images.jpg"));
imagesArrayList.add(new Image("sample/pictures/klepiahzwl921.png"));
borderPane.setPrefSize(450, 450);
pane.setPrefSize(borderPane.getPrefWidth(), borderPane.getPrefHeight());
current.fitWidthProperty().bind(pane.prefWidthProperty());
current.fitHeightProperty().bind(pane.prefHeightProperty());
Timeline timeline = new Timeline();
KeyValue transparent = new KeyValue(current.opacityProperty(), 0.0);
KeyValue opacity = new KeyValue(current.opacityProperty(), 1.0);
KeyFrame startFadeIn = new KeyFrame(Duration.ZERO, transparent);
KeyFrame endFadeIn = new KeyFrame(Duration.seconds(5), opacity);
KeyFrame startFadeOut = new KeyFrame(Duration.seconds(5), transparent);
KeyFrame endFadeOut = new KeyFrame(Duration.seconds(5.0), e ->{
count++;
current.setImage(imagesArrayList.get(count % 3));
}, transparent);
timeline.getKeyFrames().addAll(startFadeIn, endFadeIn, startFadeOut, endFadeOut);
timeline.setCycleCount(Animation.INDEFINITE);
timeline.play();
}

Using TextField with LibGDX

I am working on an Android game with LibGDX and would like to implement two TextFields to login to a server.
As far as I know I need to use Stage to add a TextField as an Actor like this:
this.stage = new Stage();
TextField txtf = new TextField("", mSkin);
//...
stage.addActor(txtf);
// And then set the stage as InputProcessor
Gdx.input.setInputProcessor(this.stage);
But I already have a custom InputHandler which implements InputProcessor. I don't really know how I can handle a TextField with my InputHandler.
I have created my TextField in my InputHandler like this:
public class InputHandler implements InputProcessor {
public InputHandler(float ratioWidth, float ratioHeight, GameWorld world) {
this.world = world;
this.player = world.getPlayer();
this.ratioWidth = ratioWidth;
this.ratioHeight = ratioHeight;
//...
this.usernameTextField = new TextField("", AssetLoader.defaultSkin);
this.usernameTextField.setPosition(24,73);
this.usernameTextField.setSize(88, 14);
this.passwordTextField = new TextField("", AssetLoader.defaultSkin);
this.passwordTextField.setPosition(24, 102);
this.passwordTextField.setSize(88, 14);
this.actors.add(this.usernameTextField);
this.actors.add(this.passwordTextField);
}
And then I have a method in my InputHandler that can get the TextField for the GameRenderer:
public ArrayList<Actor> getActors() { return this.actors; }
And this is my GameRenderer:
public class GameRenderer {
public GameRenderer(GameWorld world) {
this.world = world;
//...
}
//...
private void drawLogUI() {
for(Actor a : ((InputHandler) Gdx.input.getInputProcessor()).getActors()){
a.draw(batcher, 1);
}
//...
}
public void render(float delta) {
// Initialisation
Gdx.gl.glClearColor(32/255.0f, 72/255.0f, 132/255.0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batcher.begin();
batcher.enableBlending();
//...
drawLogUI();
//...
batcher.end();
}
//...
}
TextFields are rendering correctly but I can't do anything with them, keyboard doesn't show up, etc. Can someone explain how I can use them in my project ?
You know that you need to use Stage and TextField for your requirement, you created TextField but not adding to stage so you're not using scene2d(stage, actor, textfield..)
Tutorial that you following, don't have stage so he is using InputProcessor for his requirement.
TextField usernameTextField = new TextField("", AssetLoader.defaultSkin);
usernameTextField.setPosition(24,73);
usernameTextField.setSize(88, 14);
stage.add(usernameTextField); // <-- Actor now on stage
Gdx.input.setInputProcessor(stage);
Inside render() method call
stage.draw();
stage.act();

What's the code behind showAndWait in JavaFX?

I developed a small JavaFX application to be deployed in an Android device. Since, Alert is not yet supported in this current version of JavaFXPorts, I made my own implementaion of dialog. My problem is: I do not know how to implement the showAndWait functionality. Can someone know the idea?
Here's the code:
private static int status;
public static int showConfirm(String message){
status = 0;
black = new StackPane();
black.setStyle("-fx-background-color: black; -fx-opacity: 0.7;");
black.setPrefSize(Main.WIDTH, Main.HEIGHT);
Label label = new Label(message);
label.setStyle("-fx-font-size: 22px;");
label.setWrapText(true);
Button okBtn = new Button("OK");
okBtn.getStyleClass().add("terminal-button");
okBtn.setPrefWidth(120);
okBtn.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
status = 1;
Dialog.hide();
}
});
Button cancelBtn = new Button("Cancel");
cancelBtn.getStyleClass().add("terminal-button");
cancelBtn.setPrefWidth(120);
cancelBtn.setOnAction(new EventHandler<ActionEvent>(){
#Override
public void handle(ActionEvent event) {
status = -1;
Dialog.hide();
}
});
HBox btnContainer = new HBox(10);
btnContainer.setAlignment(Pos.CENTER_RIGHT);
btnContainer.getChildren().addAll(okBtn,cancelBtn);
VBox root = new VBox(30);
root.setStyle("-fx-background-color: white;");
root.setPadding(new Insets(20));
root.setPrefWidth(Main.WIDTH - 200);
root.getChildren().addAll(label,btnContainer);
Group container = new Group();
container.getChildren().add(root);
Main.PAGE.getChildren().add(black);
Main.PAGE.getChildren().add(container);
return status;
}

Sidescrolling over image in JavaFX

I've wrapped my brain around a challenge for 2 days now. I am all empty for ideas, so I hope someone out there know how to do this.
I got inspired by Angela Caicedo's city app, from the website https://blogs.oracle.com/acaicedo/entry/managing_multiple_screens_in_javafx, and trying to make a similar app-gui to show available rooms and lecture halls at my University.
I am using Java FX to build the gui, and I get the whole GUI printed out, which is a java fx pane with a image on it. What I want, however, is to just see a small part of the gui (the backgroundimage I am using is w:1500px h:500, so each part will be w:500px h:500px), then be able to push a button or a arrow (or similar) to move the window to the next step. On top of the image there is 3 panes with w:500px h:500px snapped to each other. Maybe this is a bad solution, considering all the pane-types Java FX has available.
So, what I need is a constrained viewer of sorts.
I've also used FMXL to build the GUI, having one FMXL document, one Controller and a css-file to handle the design.
I'm sure I've been everywhere on the internet by now, so I really hope someone has done this before in Java FX :)
Ok, here is some code example. The first sample works nice, but I want to implement the second example instead. I am reading on the TranslateTransition of JavaFX, but my efforts of trying to switch the code is hopeless..
1'st example (working, and is fading in and out of the fxml screen):
public boolean setScreen(final String name){
if (screens.get(name) != null) { //screen loaded
final DoubleProperty opacity = opacityProperty();
if (!getChildren().isEmpty()) { //if there is more than one screen
Timeline fade = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 1.0)),
new KeyFrame(new Duration(2000), new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
getChildren().remove(0); //remove the displayed screen
getChildren().add(0, screens.get(name)); //add the screen
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(2000), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
}, new KeyValue(opacity, 0.0)));
fade.play();
} else {
setOpacity(0.0);
getChildren().add(screens.get(name)); //no one else been displayed, then just show
Timeline fadeIn = new Timeline(
new KeyFrame(Duration.ZERO, new KeyValue(opacity, 0.0)),
new KeyFrame(new Duration(1000), new KeyValue(opacity, 1.0)));
fadeIn.play();
}
return true;
} else {
System.out.println("screen hasn't been loaded!!! \n");
return false;
}
}
Second example, the TranslateTransition I want to implement instead:
private final double IMG_WIDTH = 500;
private final double IMG_HEIGHT = 500;
private final int NUM_OF_IMGS = 3;
private final int SLIDE_FREQ = 4; // in secs
#Override
public void start(Stage stage) throws Exception {
stage.initStyle(StageStyle.UNDECORATED);
StackPane root = new StackPane();
Pane clipPane = new Pane();
// To center the slide show incase maximized
clipPane.setMaxSize(IMG_WIDTH, IMG_HEIGHT);
clipPane.setClip(new Rectangle(IMG_WIDTH, IMG_HEIGHT));
HBox imgContainer = new HBox();
ImageView imgGreen = new ImageView(new Image(getClass().getResourceAsStream("uib_01.jpg")));
ImageView imgBlue = new ImageView(new Image(getClass().getResourceAsStream("uib_02.jpg")));
ImageView imgRose = new ImageView(new Image(getClass().getResourceAsStream("uib_03.jpg")));
imgContainer.getChildren().addAll(imgGreen, imgBlue, imgRose);
clipPane.getChildren().add(imgContainer);
root.getChildren().add(clipPane);
Scene scene = new Scene(root, IMG_WIDTH, IMG_HEIGHT);
stage.setTitle("Image Slider");
stage.setScene(scene);
startAnimation(imgContainer);
stage.show();
}
private void startAnimation(final HBox hbox) {
EventHandler<ActionEvent> slideAction = (ActionEvent t) -> {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1.5), hbox);
trans.setByX(-IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
EventHandler<ActionEvent> resetAction = (ActionEvent t) -> {
TranslateTransition trans = new TranslateTransition(Duration.seconds(1), hbox);
trans.setByX((NUM_OF_IMGS - 1) * IMG_WIDTH);
trans.setInterpolator(Interpolator.EASE_BOTH);
trans.play();
};
List<KeyFrame> keyFrames = new ArrayList<>();
for (int i = 1; i <= NUM_OF_IMGS; i++) {
if (i == NUM_OF_IMGS) {
keyFrames.add(new KeyFrame(Duration.seconds(i * SLIDE_FREQ), resetAction));
} else {
keyFrames.add(new KeyFrame(Duration.seconds(i * SLIDE_FREQ), slideAction));
}
}
Timeline anim = new Timeline(keyFrames.toArray(new KeyFrame[NUM_OF_IMGS]));
anim.setCycleCount(Timeline.INDEFINITE);
anim.playFromStart();
}
The screen should change on button click. I have this in a separate controller class:
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
public class roomAppController implements Initializable, ScreenController {
private ScreenPane myScreenPane;
#FXML
public ImageView bldArw_1;
public ImageView rmArw_1;
#FXML
private void handleExitButtonEvent(MouseEvent e) {
System.out.println("Button is clicked");
System.exit(0);
}
#FXML
private void handleNextPageEvent(MouseEvent e) {
if((ImageView)e.getSource() == bldArw_1) {
myScreenPane.setScreen("buildingScreen");
}
if((ImageView)e.getSource() == rmArw_1) {
myScreenPane.setScreen("roomScreen");
}
System.out.println("Clicked");
}
#Override
public void initialize(URL location, ResourceBundle resources) {
}
#Override
public void setScreenPane(ScreenPane screenPage) {
myScreenPane = screenPage;
}
}

Categories

Resources