-1

I am a beginner in javaFX and am stuck in this one area. Any help will be appreciated a lot. This is sample app I have made for clear understanding using scene builder. There is a text area and a button.I want to set data into the text area on the button click. The setting happens in another thread. The code is as follows:

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

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.stage.Stage;

public class TpController{

    @FXML
    private ScrollPane scrollPane;

    @FXML
    private Button button;

    @FXML
    public TextArea txtArea ;

    private Stage stage;

    public void setTextArea(TextArea txt)
    {
        this.txtArea = txt ;
    }
    public TextArea getTextArea()
    {
        return txtArea;
    }

    public void setStage(Stage stage)
    {
        this.stage = stage;
    }

    public Stage getStage()
    {
        return stage;
    }
    public void setTopText(String text) {
       // set text from another class
       txtArea.setText(text);
    }

public void buttonHandler()
{

    tpThread t = new tpThread();
    t.start();
}

The tpThread class is as follows:

import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.TextArea;
import javafx.stage.Stage;

public class tpThread extends Thread {

@Override
public void run() {
// TODO Auto-generated method stub

FXMLLoader loader = new FXMLLoader(getClass().getResource("Justtp.fxml"));
try {
    Parent root = (Parent) loader.load();
    } 
catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
TpController myController = loader.getController();
TextArea t =  myController.getTextArea();
String data = "hi\nhello\nhow are you\nnice to meet you\nhahaha";

//System.out.println(t.setData("hi"));
myController.setTopText(data);
}

Instead of using setTopText, i have also directly used

t.setText(data);

But no use. My final output does nothing on the button click.

NiyatiShah
  • 41
  • 2

1 Answers1

0

There are many issues with your code.

  1. Modifications to the active scene graph off of the JavaFX application thread must be performed via Platform.runLater().
  2. You don't need another thread to accomplish something on a button click.
  3. Loading an FXML as you do in your code and not attaching the resultant node to a scene is pointless as the user will never see anything that is not attached to a scene.

There may be other issues with your code which cause it not to work as you expect.

In general, for assistance debugging an issue, provide an mcve. Note it should be both minimal and complete so that somebody could copy and paste the code to replicate the issue (and pretty much nothing else).

Community
  • 1
  • 1
jewelsea
  • 150,031
  • 14
  • 366
  • 406