簡體   English   中英

JavaFX label 文字不會更新

[英]JavaFX label text won't update

正如標題所示,我正在嘗試通過從單獨的 class 提供一個字符串值來動態更改我的 label object(傳入消息)。這個單獨的 class 稍后將成為在另一個 88398181219 上運行的 UDP 客戶端獲取另一個 label 以根據文本字段中的文本進行更改,但傳入的消息是從掃描儀輸入字符串,然后調用 settext() 。 我唯一的問題是傳入消息不會更新。 字符串傳遞到 controller class 沒問題。 代碼:

我的總機 class:

package application;

import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.paint.Color;

public class Main extends Application 
{
    @FXML
    Image icon = new Image("UDPChatIcon.png");
    static Messages msg = new Messages();
    
    public static void main(String[] args) 
    {
        msg.start();
        launch(args);
    }

    @Override
    public void start(Stage arg0) throws Exception 
    {
        Stage stage = new Stage();
        Parent root = FXMLLoader.load(getClass().getResource("UDPChatRoom.fxml"));
        
        Scene scene = new Scene(root, 600, 800, Color.BLACK);
        scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
        
        stage.setResizable(false);
        stage.getIcons().add(icon);
        stage.setTitle("UPD Chatroom");
        stage.setScene(scene);
        stage.show();
    }

}

我的 controller class:

package application;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;

public class controller
{
    @FXML AnchorPane aPane;
    @FXML GridPane gPane;
    @FXML Button btn;
    @FXML Label message;
    @FXML static Label incomingmessage = new Label();
    @FXML static String test = "test";
    @FXML Messages msg = new Messages();
    @FXML TextField inputbox;

    @FXML
    public void sendpressed(ActionEvent e) 
    {       
        updatemessage();
    }
    
    @FXML
    public static void receive(String msg) 
    {
        System.out.println("Incoming Message @controller: " + msg);
        incomingmessage.setText(msg);
        System.out.println("changed");
    }
    
    @FXML
    public void updatemessage() 
    {
        message.setText(inputbox.getText());
    }
    
}

這個 class 是我用來將字符串發送到 controller 的。這僅用於更改變量incomingmessage 同樣,這些字符串稍后將來自 UDP 客戶端,但我現在只關注 GUI。

package application;

import java.util.Scanner;

public class Messages implements Runnable
{
    private static String input = "default";
    
    public void start() 
    {
        Thread thread = new Thread(new Messages());
        thread.start();
    }

    public void run() 
    {
        try {
            // Displaying the thread that is running
            while(true) 
            {
                Scanner in = new Scanner(System.in);
                System.out.print("Enter Text: ");
                input = in.nextLine();
                System.out.println("inputted Message @Messages: " + input);
                send(input);
            }
        }
        catch (Exception e) {
            // Throwing an exception
            System.out.println("Exception is caught: " + e.getMessage());
        }
    }
    
    public void send(String message) 
    {
        System.out.println("sending @Messages: " + message);
        
        controller.receive(message);
    }
    
    public String getInput() 
    {
        return input;
    }

}

和我的 FXML 文件

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.Insets?>
<?import javafx.scene.Cursor?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.ColumnConstraints?>
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.layout.RowConstraints?>

<AnchorPane fx:id="aPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="800.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.controller">
   <cursor>
      <Cursor fx:constant="DEFAULT" />
   </cursor>
   <children>
      <Button fx:id="btn" layoutX="507.0" layoutY="761.0" mnemonicParsing="false" onAction="#sendpressed" prefHeight="25.0" prefWidth="79.0" text="Send" AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="501.0" AnchorPane.rightAnchor="20.0" AnchorPane.topAnchor="755.0" />
      <TextField id="input" fx:id="inputbox" layoutX="11.0" layoutY="761.0" prefHeight="25.0" prefWidth="478.0" promptText="Enter Message Here..." AnchorPane.bottomAnchor="20.0" AnchorPane.leftAnchor="20.0" AnchorPane.rightAnchor="102.0" AnchorPane.topAnchor="755.0" />
      <GridPane fx:id="gPane" prefHeight="742.0" prefWidth="550.0" style="-fx-background-color: BLACK; -fx-background-radius: 20; -fx-border-color: darkgrey; -fx-border-width: 10; -fx-border-radius: 10;" AnchorPane.bottomAnchor="65.0" AnchorPane.leftAnchor="20.0" AnchorPane.rightAnchor="20.0" AnchorPane.topAnchor="20.0">
        <columnConstraints>
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
          <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
        </columnConstraints>
        <rowConstraints>
          <RowConstraints maxHeight="243.0" minHeight="0.0" prefHeight="0.0" vgrow="SOMETIMES" />
          <RowConstraints maxHeight="741.0" minHeight="10.0" prefHeight="741.0" vgrow="SOMETIMES" />
          <RowConstraints maxHeight="26.0" minHeight="0.0" prefHeight="0.0" vgrow="SOMETIMES" />
        </rowConstraints>
         <children>
            <Label id="incomingmessage" fx:id="incomingmessage" alignment="TOP_LEFT" contentDisplay="CENTER" prefHeight="748.0" prefWidth="280.0" style="-fx-text-fill: Red; -fx-border-color: grey; -fx-border-radius: 5;" wrapText="true" GridPane.rowIndex="1">
               <padding>
                  <Insets left="10.0" />
               </padding></Label>
            <Label id="message" fx:id="message" alignment="TOP_LEFT" contentDisplay="CENTER" prefHeight="783.0" prefWidth="280.0" style="-fx-text-fill: lightblue; -fx-border-width: 2; -fx-border-color: grey; -fx-border-radius: 5;" wrapText="true" GridPane.columnIndex="1" GridPane.rowIndex="1">
               <padding>
                  <Insets left="10.0" right="10.0" />
               </padding></Label>
         </children>
      </GridPane>
   </children>
</AnchorPane>

我想我會試試這個。 從我運行的測試來看,在調用它的任何方法時, Scanner都會出現阻塞。 我嘗試了BufferedReader ,它最初顯示了相同的行為。 然后我使用了BufferedReader's ready方法,它似乎可以工作。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import javafx.application.Application;
import javafx.concurrent.ScheduledService;
import javafx.concurrent.Task;
import javafx.scene.Scene;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.Duration;

/**
 *
 * @author Sedrick(sedj601)
 */
public class App extends Application{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) throws Exception {
        TextArea textArea = new TextArea();
        
        ScheduledService<String> scheduledService = new ScheduledService<String>() {
            @Override
            protected Task<String> createTask() {
                return getScannerLine();
            }
        };
        scheduledService.setOnSucceeded((t) -> {
            String output = scheduledService.getValue();
            if(output.length() > 0)
            {
                textArea.appendText(output + System.lineSeparator());
            }            
        });
        scheduledService.setPeriod(Duration.seconds(1));
        
        
        
        HBox root = new HBox(textArea);
        stage.setScene(new Scene(root, 700, 500));
        stage.show();        
        
        scheduledService.start();
    }   
    
    final BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
    public Task<String> getScannerLine()
    {       
        Task<String> task = new Task() {
            @Override
            protected Object call() throws Exception { 
                if(br.ready())
                {
                    return br.readLine();
                }
                
                return "";
            }
        };
        
        return task;
    }    
}

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM