2017-03-14 2 views
0

내 프로그램에는 두 개의 FormChecked 클래스가 있습니다.다른 클래스의 레이블에 텍스트 추가. Java

Form 클래스에는 LabelButton이 있습니다. Button의 클릭에서 클래스 Checked의 인스턴스를 만들고 스레드를 시작합니다.

이제 문제는 Checked 클래스의 텍스트를 전달하고 Label 값을 변경해야하지만 성공하지 못했습니다. 여기

내 코드입니다 :

public class MainForm extends Application { 
    protected static int intVerifiedNews = 0; 
    Button btnPlay = new Button("Button"); 
    Label lbVerifiedNews = new Label("News: "); 
    @Override 
    public void start(Stage primaryStage) throws IOException { 

     final BorderPane border = new BorderPane(); 
     final HBox hbox = addHBox(); 

     Scene scene = new Scene(border, 850, 500, Color.BLACK); 

     btnPlay.setPrefSize(100, 24); 
     btnPlay.setMinSize(24, 24); 

     btnPlay.setOnAction((event) -> { 
        Checked ch = new Checked(); 
        ch.start(); 
       } 
     ); 

     border.setTop(hbox); 
     hbox.getChildren().addAll(btnPlay, lbVerifiedNews); 
     primaryStage.setScene(scene); 
     primaryStage.show(); 

    } 
    private HBox addHBox() { 
     HBox hbox = new HBox(); 
     hbox.setPadding(new Insets(5, 0, 5, 5)); 
     return hbox; 
    } 

    public static void main(String[] args) throws IOException { 
     launch(args); 
    } 
} 

검사 클래스 :

public class Checked extends Thread { 


    public void run() { 
     for (int i = 0; i <= 5; i++) { 
    MainForm.intVerifiedNews ++; 
//Here you need to pass the intVerifiedNews value to the Label 
       System.out.println(MainForm.intVerifiedNews); 
     } 

    } 
} 

답변

0

Checked 클래스의 생성자 내로 통과 lbVerifiedNews 및 필드이 참조를 저장한다. 스레드 "스레드 7"java.lang.IllegalStateException에서

Checked ch = new Checked(lbVerifiedNews);

public class Checked extends Thread { 

    Label checkedLabelReference; 
    public Checked(Label label){ 
     this.checkedLabelReference = label; 
    } 

    public void run() { 
     for (int i = 0; i <= 5; i++) { 
      MainForm.intVerifiedNews ++; 
      //Here you need to pass the intVerifiedNews value to the Label 
      Platform.runLater(new Runnable() { 
       @Override public void run() { 
        checkedLabelReference.setText(MainForm.intVerifiedNews);//update text 
      }}); 
      System.out.println(MainForm.intVerifiedNews); 
     } 

    } 
} 
+0

예외 :하지 FX 응용 프로그램 스레드에서; currentThread = Thread-7 – MTiS

+0

이 코드가'Platform.runLater (...)'로 업데이트되었습니다. 내 자신을 시험하지 마십시오. –

+0

남자, 당신은 마술사입니다. 정말 고맙습니다) – MTiS

0

일반적으로 당신이 그래서 당신의 Checked 클래스로 업데이트 할 MainForm 또는 양식 객체에 대한 참조를 전달하려는 것 직접 업데이트 방법에 액세스 할 수 있어야합니다.

public class Checked implements Runnable { 

    public Checked(MainForm form1) { 
    // store form (or the object representing the text box directly) to update later 
    } 

    public void run() { 
    } 
}