Duvida Label javafx

Como eu faço para alterar o valor de um label Javafx utilizando o valor de uma variavel ?
abaixo segue o codigo

`package termoplayer;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

import java.io.File;

import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;

public class MainApp extends Application implements Initializable {

private Stage primaryStage;
private BorderPane rootLayout;
private static String workingDir = System.getProperty("user.dir");
private static File f = new File(workingDir, "src\\videoteste.mp4");
private static Media m = new Media(f.toURI().toString());
private static MediaPlayer mp = new MediaPlayer(m);
@FXML
MediaView mv = new MediaView(mp);
@FXML
Label lblLabel = new Label();


@Override
public void start(Stage primaryStage) {
	this.primaryStage = primaryStage;
	this.primaryStage.setTitle("TermoPlayer Itaipava");
	initRootLayout();
	showPersonOverview();
	
	mv.setPreserveRatio(true);
	mp.setCycleCount(MediaPlayer.INDEFINITE);
	mp.play();
	
	//Thread t1 = new Thread(new VerificaSerial());
	//t1.start()	;
	
}
/**
 * Inicializa o root layout (layout base).
 */
public void initRootLayout() {
	try {
		// Carrega o root layout do arquivo fxml.
		FXMLLoader loader = new FXMLLoader();
		loader.setLocation(MainApp.class.getResource("view/RootLayout.fxml"));
		rootLayout = (BorderPane) loader.load();
		// Mostra a scene (cena) contendo o root layout.
		/* final */Scene scene = new Scene(rootLayout);
		rootLayout.getChildren().add(mv);
		primaryStage.setScene(scene);
		primaryStage.setFullScreen(true);
		primaryStage.show();

	} catch (IOException e) {
		e.printStackTrace();
	}
}

/**
 * Mostra o person overview dentro do root layout.
 */
public void showPersonOverview() {
	try {
		// Carrega o person overview.
		FXMLLoader loader = new FXMLLoader();
		loader.setLocation(MainApp.class.getResource("view/PersonOverview.fxml"));
		AnchorPane personOverview = (AnchorPane) loader.load();

		// Define o person overview dentro do root layout.
		rootLayout.setCenter(personOverview);
	} catch (IOException e) {
		e.printStackTrace();
	}
}

/**
 * Retorna o palco principal.
 * 
 * @return
 */


public static void main(String[] args) {
	launch(args);
	System.out.println("TEste aqui ");
	
}


public Stage getPrimaryStage() {
	return primaryStage;
}
public void setPrimaryStage(Stage primaryStage) {
	this.primaryStage = primaryStage;
}
public BorderPane getRootLayout() {
	return rootLayout;
}
public void setRootLayout(BorderPane rootLayout) {
	this.rootLayout = rootLayout;
}
public String getWorkingDir() {
	return workingDir;
}
public void setWorkingDir(String workingDir) {
	this.workingDir = workingDir;
}
public File getF() {
	return f;
}
public void setF(File f) {
	this.f = f;
}
public Media getM() {
	return m;
}
public void setM(Media m) {
	this.m = m;
}
public MediaPlayer getMp() {
	return mp;
}
public void setMp(MediaPlayer mp) {
	this.mp = mp;
}
public MediaView getMv() {
	return mv;
}
public void setMv(MediaView mv) {
	this.mv = mv;
}
public Label getLblLabel() {
	return lblLabel;
}
public static void setLblLabel(String value) {
	lblLabel.setText(value); 
}
@Override
public void initialize(URL location, ResourceBundle resources) {
	
	// TODO Auto-generated method stub
}

}`

Bom primeiramente, eu não vi vc add o Label a sua Stage em nenhum momento, e to vendo q vc ta usando a tag #FXML essa tag vc só usa se for referenciar esse objeto como id do objeto no Fxml, se vc já ta com esse objeto referenciado no layout e vc dá new Label, como se ele se tornasse outro objeto, e não aquele q foi referenciado no layout FXML.

recomendo que fique assim e com atributo privado:

@FXML
private Label lblLabel;

caso não seja possível utilizar essa forma pois funciona corretamente usando o padrão MVC que acho o mais correto para aplicação JavaFX na minha opinião. Então apenas adicione esse label ao seu Stage.
e recomendo a leitura deste: Tutorial JavaFX 8

Fiz as mudanças que falou seguindo o tutorial, agora tambem consegui separar melhor e fazer no modelo MVC.
agora além de não conseguir mudar a label tbm não consigo inciar o video que roda no background usando mediaview

vou compartilhar aqui as classes completas.

Person.java
`package termoplayer.model;

import java.awt.Label;
import java.io.File;

import javafx.fxml.FXML;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;

public class Person {

private static String workingDir = System.getProperty("user.dir");
private static File f = new File(workingDir, "src\\videoteste.mp4");
private static Media m = new Media(f.toURI().toString());
private static MediaPlayer mp = new MediaPlayer(m);

//@FXML
//MediaView mv = new MediaView(mp);
//@FXML
//private Label lblLabel; 

/**
 *  Construtor padrão.
 */
public Person() {
    this(null, null);
}
    /**
     * Construtor com alguns dados iniciais.
     * 
     * 
     */
    public Person(File f, MediaPlayer mp) {
       
    	rootLayout.getChildren().add(mv); // a 1 ERRO NESSA LINHA e NA DE BAIXO 
    	mv.setPreserveRatio(true);
		mp.setCycleCount(MediaPlayer.INDEFINITE);
		mp.play();
	       }

}
classe MainApp.javapackage termoplayer;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
import termoplayer.view.PersonOverviewController;

import java.io.File;

import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;

public class MainApp extends Application {

private Stage primaryStage;
public static BorderPane rootLayout;

/*
private static String workingDir = System.getProperty("user.dir");
private static File f = new File(workingDir, "src\\videoteste.mp4");
private static Media m = new Media(f.toURI().toString());
private static MediaPlayer mp = new MediaPlayer(m);
@FXML
MediaView mv = new MediaView(mp);
@FXML
Label lblLabel; //= new Label();
*/

@Override
public void start(Stage primaryStage) {
	this.primaryStage = primaryStage;
	this.primaryStage.setTitle("TermoPlayer Itaipava");
	initRootLayout();
	showPersonOverview();
}
	/*
	mv.setPreserveRatio(true);
	mp.setCycleCount(MediaPlayer.INDEFINITE);
	mp.play();
	//lblLabel.setText("51");
	
	//Thread t1 = new Thread(new VerificaSerial());
	//t1.start()	;
	
}
/**
 * Inicializa o root layout (layout base).
 */
public void initRootLayout() {
	try {
		// Carrega o root layout do arquivo fxml.
		FXMLLoader loader = new FXMLLoader();
		loader.setLocation(MainApp.class.getResource("view/RootLayout.fxml"));
		rootLayout = (BorderPane) loader.load();
		// Mostra a scene (cena) contendo o root layout.
		Scene scene = new Scene(rootLayout);
		//rootLayout.getChildren().add(mv);
		primaryStage.setScene(scene);
		primaryStage.setFullScreen(true);
		primaryStage.show();

	} catch (IOException e) {
		e.printStackTrace();
	}
}

/**
 * Mostra o person overview dentro do root layout.
 */
public void showPersonOverview() {
	try {
		// Carrega o person overview.
		FXMLLoader loader = new FXMLLoader();
		loader.setLocation(MainApp.class.getResource("view/PersonOverview.fxml"));
		AnchorPane personOverview = (AnchorPane) loader.load();

		// Define o person overview dentro do root layout.
		rootLayout.setCenter(personOverview);
		
		 // Dá ao controlador acesso à the main app.
        PersonOverviewController controller = loader.getController();
        controller.setMainApp(this);
        
	} catch (IOException e) {
		e.printStackTrace();
	}
}

/**
 * Retorna o palco principal.
 * 
 * @return
 */

public Stage getPrimaryStage() {
    return primaryStage;
}

public static void main(String[] args) {
	launch(args);
	System.out.println("Finaliza aqui ");
	
}

}`

PersonOverviewController.java
`package termoplayer.view;

import java.awt.Label;

import javafx.fxml.FXML;
import javafx.scene.media.MediaView;
import termoplayer.MainApp;

public class PersonOverviewController {

@FXML
MediaView mv;
@FXML
private Label lblLabel; 

private MainApp mainApp;
/**
 * O construtor.
 * O construtor é chamado antes do método inicialize().
 */
public PersonOverviewController() {
}

/**
 * Inicializa a classe controller. Este método é chamado automaticamente
 *  após o arquivo fxml ter sido carregado.
 */
@FXML
private void initialize() {
    // Inicializa a tablea de pessoa com duas colunas.
   
	/**
     * É chamado pela aplicação principal para dar uma referência de volta a si mesmo.
     * 
     * @param mainApp
     */
}
    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp; 	
    }
}`

cara isso ai ta muito errado a maneira q vc ta fazendo, vc apenas “copiou” o código de tutorial e tentou mudar alguma coisa, mas vc não pegou a lógica nesse caso:
É o seguinte, vc vai criar um layout FXML, editar ele com o Scene Builder.
Ao criar os componentes vc vai atribuir eles ao seu Objeto no código usando a tag @FXML:
ex:

@FXML
private MediaView video;

e no Scene Builder vc vai atribuir o layout a esse objeto da seguinte forma:


veja o fx:id que eu atribui o objeto da Classe que faz o controle deste layout.
Dica: Para todo layout que vc for fazer crie uma Classe de Controle para cada um! e não esqueça nunca de atribuir essa classe controle ao Layout(Usando o scene Builder) isso está no tutorial q eu te enviei.
e nunca esqueça de colocar na Sua Classe de controle o método:

@FXML
private void initialize(){
}

esse método que vai inicializar os componentes do layout automaticamente ok!
Para reproduzir um vídeo, coloque uma MediaView no layout usando o Scene Builder e adicione a sua Classe de controle sua MediaView q nem eu mostrei no inicio.
os outros vc deixa dessa forma:

private MediaPlayer player;
private Media media;

Dica: crie um método executarFunção.
ex:

public void executarFuncao() {
        String caminhoVideo = "file:" +Gerenciador.getUsers() + System.getProperty("user.name") + "/Google Drive/Desenvolvedor/Media/Tutorial.mp4";
        String replace = this.caminhoVideo.replace(" ", "%20").replace("\\", "/");
        this.media = new Media(replace);
        this.player = new MediaPlayer(media);
        this.video.setMediaPlayer(player);
        this.player.play();
    }

Ai na sua classe q inicia o javaFX(Start), utilize desta forma:

FXMLLoader carregar = new FXMLLoader(PrincipalFX.class.getClassLoader().getResource("jeanderson/br/view/TelaNoviVideo.fxml"));
BorderPane tela = (BorderPane) carregar.load();
Stage palcoNovidade = new Stage();
Scene cena = new Scene(tela);
palcoNovidade.setScene(cena);
//olha a classe de controle logo a baixo
TelaNoviVideoControl control = carregar.getController();
//mostro palco
palcoNovidade.show();
//logo após utilizando a Classe controle inicio o video:
control.executarFuncao();

Pegue os conceitos do tutorial, entenda e depois faça uma da sua maneira utilizando os conceitos que vc aprendeu com o tutorial. Provavelmente vc terá dúvidas então pode perguntar que estou todo ouvidos :slight_smile:

1 curtida

String caminhoVideo = "file:" +Gerenciador.getUsers() + System.getProperty("user.name") + "/Google Drive/Desenvolvedor/Media/Tutorial.mp4";

o que seria o Gerenciador ?

Esse Gerenciador é uma classe que fiz para gerenciar determinadas funções, ele tem um método estático que me retornar as path padrão do sistema ex:

if(System.getProperty("os.name").startsWith("Windows"){
     return "/Users/";
}else if(System.getProperty("os.name").startsWith("Linux"){
     return "/home/";
}

Basicamente é isso

1 curtida