0
這是我用JavaFX編寫的第一個程序(與Swing相對)。我從一個簡單的按鈕矩陣顯示數據集開始很小(我不想僅僅使用一個表)。JavaFX中的按鈕矩陣(如何創建和排列)
package matrixjavafx;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import java.util.Random; // required for random number generation
/**
*
* @author Matt
*/
public class MatrixJavaFX extends Application {
Button[][] matrix; //names the grid of buttons
@Override
public void start(Stage primaryStage) {
int SIZE = 10;
int length = SIZE;
int width = SIZE;
StackPane root = new StackPane();
matrix = new Button[width][length]; // allocates the size of the matrix
// runs a for loop and an embedded for loop to create buttons to fill the size of the matrix
// these buttons are then added to the matrix
for(int y = 0; y < length; y++)
{
for(int x = 0; x < width; x++)
{
Random rand = new Random(); // Creates new Random object for generating random numbers
// The following variables are generated using Random object rand.
// rand.nextInt(2) generates a double ranging from 0.000 to 0.999.
// setting the target variable to be an integer truncates the range to 0 - 1.
int rand1 = rand.nextInt(2); // Declare and initialize random integer (0 - 1) + 1
matrix[x][y] = new Button(/*"(" + rand1 + ")"*/); //creates new random binary button
matrix[x][y].setText("(" + rand1 + ")"); // Sets the text inside the matrix
matrix[x][y].setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
System.out.println("Random Binary Matrix (JavaFX)");
}
});
root.getChildren().add(matrix[x][y]);
}
}
Scene scene = new Scene(root, 500, 500);
primaryStage.setTitle("Random Binary Matrix (JavaFX)");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
greeting(); // Greets the User and explains the purpose of the program
launch(args); // Opens the window that generates and displays the matrix
//new MatrixSwingGUI(width, length); // makes new MatrixSwing with 2 parameters
thanks(); // Thanks User and indicates that the program is about to close
}
public static void greeting()
{
// Greets the User and displays the program's purpose
System.out.println("Welcome to the Random Matrix Generator\n");
System.out.println("The purpose of this program is to generate and display "
+ "\na 10 x 10 matrix of random 0's, and 1's.");
}
public static void thanks() // Thanks User and indicates that the program is about to close
{
System.out.println("\nGoodbye and Thank You for using the Random Matrix Generator\n\n");
} // End thanks method
}
問題的心臟似乎是以下行,因爲默認情況下,所有的按鈕在面板的中央是堆疊在彼此的頂部。
StackPane root = new StackPane();
這就是說,我想讓按鈕對齊所有長度和寬度,從而得到一個n×m的矩陣。應該怎麼做才能做到這一點?需要導入哪些額外的javafx.scene。*文件?