該程序假設將程序中的值存儲到按下寫入按鈕時。然後當按下讀取時,它將讀取並顯示值。結果應該顯示在文本區域中。但是,運行該程序時,按鈕不顯示。當我運行它時,java開始在我的電腦上運行,但沒有出現。Java FX文本框不工作
package program;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Arrays;
import java.util.Date;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class program extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws ClassNotFoundException, IOException {
// Text area
TextArea textArea = new TextArea();
textArea.setStyle("-fx-background-color: lightgrey; -fx-text-fill: blue; -fx-control-inner-background: grey");
textArea.setPadding(new Insets(15, 15, 15, 15));
Button write = new Button("Write");
write.setOnAction(e -> {
// Create an output stream for file
try(ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("Exercise17_05.dat", true))) {
int[] numbers = {1, 2, 3, 4, 5};
// Write to file
// 1. Write double
output.writeDouble(5.5);
// 2. Write int array object
output.writeObject(numbers);
// 3. Write date object
output.writeObject(new java.util.Date());
// 4. Write utf string
output.writeUTF("Exercise17_05.dat");
} catch(IOException exception) {
System.exit(0);
}
});
Button read = new Button("Read");
read.setOnAction(e -> {
//Create an input stream for file
try(ObjectInputStream input = new ObjectInputStream(new FileInputStream("Exercise17_05.dat"));){
// Read from file
// 1. Read double
double doubleValue = input.readDouble();
textArea.appendText("Double value: " + doubleValue);
// 2. Read int array object
int[] newNumbers = (int[]) (input.readObject());
textArea.appendText("Integers: " + Arrays.toString(newNumbers));
// 3. Read date object
Date date = (java.util.Date) (input.readObject());
textArea.appendText("DateTime: " + date);
// 4. Read utf string
String fileName = input.readUTF();
textArea.appendText("File name: " + fileName);
} catch(IOException | ClassNotFoundException exception) {
System.exit(0);
}});
HBox hButtons = new HBox(read, write);
VBox vProgram = new VBox(8);
vProgram.getChildren().addAll(hButtons, textArea);
primaryStage.setScene(new Scene(vProgram));
primaryStage.setTitle("Write and Read");
primaryStage.show();
}
}
這只是正常的我。我複製並粘貼代碼並運行它,按鈕和文本顯示並按預期工作。 –
這些按鈕沒有顯示給我。只顯示標題的灰色框。 – goblin
可能你沒有保存或重新編譯你的最新版本:代碼中沒有任何錯誤。清理並重建項目(或者IDE中的任何等價物)。 –