该程序假设将程序中的值存储到按下写入时。然后,当按下读取时,它将读取并显示值。结果应该显示在文本区域中。但是,运行程序时按钮不会显示。当我运行它时,java开始在我的计算机上运行,但什么都没有出现。
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();
}
}
答案 0 :(得分:3)
在代码末尾添加这两行代码,以使您的gui可见
primaryStage.setScene(new Scene(vProgram, 300, 250));
primaryStage.show();