我正在开发一个 JavaFX 项目,以展示 8 个皇后问题的解决方案。我遇到了一个奇怪的问题,其中我的场景总是呈现空,而且我似乎无法解决该问题。
我尝试在项目中渲染其他简单的东西,它们显示正确,这表明我将标签添加到 GridPane 的方式有问题。但我直接从教科书上复制了这个解决方案,所以它应该可以工作,我无法理解为什么没有显示任何内容。标题已设置且可见,但网格 Pane 应为空的位置。
package sample;
import com.sun.glass.ui.Size;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class Main extends Application {
public static final int SIZE = 8;
private int [] queens = { -1,-1,-1,-1,-1,-1,-1,-1};
@Override
public void start(Stage primaryStage) throws Exception{
search();// look for a solution
GridPane chessBoard = new GridPane();
chessBoard.setAlignment(Pos.CENTER);
Label[][] labels = new Label[SIZE][SIZE];
for(int i = 0; i < SIZE; i++)
{
for(int j = 0; j < SIZE; j++)
{
chessBoard.add(labels[i][j] = new Label(), j, i);
labels[i][j].setStyle("−fx−border−color: black");
labels[i][j].setPrefSize(55,55);
}
}
Image img = new Image("queen.png");
for(int i = 0; i < SIZE; i++)
{
labels[i][queens[i]].setGraphic(new ImageView(img));
}
Scene scenes = new Scene(chessBoard, 55 * SIZE, 55 * SIZE);
primaryStage.setTitle("Eight Queens");
primaryStage.setScene(scenes);
primaryStage.show();
}
private boolean search()
{
int k = 0;
while( k >= 0 && k < SIZE)
{
int j = findPosition(k);
if(j < 0)
{
queens[k] = -1;
k--;
}else
{
queens[k]=j;
k++;
}
}
if(k == -1)
return false;
else
return true;
}
public int findPosition(int k)
{
int start = queens[k]+1;
for(int j = start; j < SIZE; j++)
{
if(isValid(k,j))
return j;
}
return -1;
}
public boolean isValid(int row, int col)
{
for (int i = 1; i <= row; i++)
{
if( queens[row - i] == col ||
queens[row - i] == col - i ||
queens[row - i] == col + i
)
{
return false;
}
}
return true;
}
public static void main(String[] args) {
launch(args);
}
}
是的,我已经查看了具有类似标题的其他主题,但这些问题源于不同的原因。
您可以提供的任何见解都会被采纳!
最佳答案
我使用不同尺寸的图像测试了您的代码。
宽度和高度在64px时可以正常显示,当你增加到256px时,虽然无法显示图像
直接将ImageView
添加到GridPane
中可以解决您的问题,您可能需要找到一种绘制边框的方法。
for(int i = 0; i < SIZE; i++)
{
for(int j = 0; j < SIZE; j++)
{
chessBoard.add(new ImageView(isqueen(i,j)?queenimg:img), i, j);
}
}
关于JavaFX 场景始终为空;显示空舞台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60795582/