在JavaFX中使用新按钮动态更新网格窗格->;如何重新油漆?
我有一个网格窗格,其中包含许多按钮(通常介于10到25之间),每行有五个按钮(最后一行还有多少按钮)。在程序执行期间,按钮的数量(以及按钮本身)可能会发生变化。出现这种情况时,应显示新按钮。我怎样才能做到这一点?以下是一个小示例:在JavaFX中使用新按钮动态更新网格窗格->;如何重新油漆?,java,javafx,Java,Javafx,我有一个网格窗格,其中包含许多按钮(通常介于10到25之间),每行有五个按钮(最后一行还有多少按钮)。在程序执行期间,按钮的数量(以及按钮本身)可能会发生变化。出现这种情况时,应显示新按钮。我怎样才能做到这一点?以下是一个小示例: public class GridButtons extends Application { List<String> buttonTexts = new ArrayList<>(); GridPane buttonGrid =
public class GridButtons extends Application {
List<String> buttonTexts = new ArrayList<>();
GridPane buttonGrid = new GridPane();
GridPane bgGrid = new GridPane();
@Override
public void start(Stage primaryStage) {
Button changeButtonsButton = new Button("Change BTNs");
changeButtonsButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent event) {
changeButtonTexts();
}
});
bgGrid.add(changeButtonsButton, 0, 0);
changeButtonTexts();
bgGrid.add(buttonGrid, 1, 0);
Scene scene = new Scene(bgGrid, 440, 140);
primaryStage.setScene(scene);
primaryStage.show();
}
public void updateButtonsGrid() {
buttonGrid = new GridPane();
for (int i = 0; i < buttonTexts.size(); i++) {
Button button = new Button(buttonTexts.get(i));
button.setMinWidth(70);
button.setMaxWidth(70);
buttonGrid.add(button, i % 5, i / 5);
System.out.println(buttonTexts.get(i));
}
// now the new GridPane should be displayed -> how?
}
public void changeButtonTexts() {
buttonTexts.clear();
Random random = new Random();
int buttonCount = random.nextInt(15) + 10;
for (int i = 0; i < buttonCount; i++) {
buttonTexts.add("Button " + i);
}
updateButtonsGrid();
}
public static void main(String[] args) {
launch(args);
}
}
公共类GridButtons扩展应用程序{
List buttonexts=new ArrayList();
GridPane buttonGrid=新建GridPane();
GridPane bgGrid=新建GridPane();
@凌驾
公共无效开始(阶段primaryStage){
按钮更改按钮按钮=新按钮(“更改基站”);
changeButtonsButton.setOnAction(新的EventHandler(){
@凌驾
公共无效句柄(ActionEvent事件){
changebuttonexts();
}
});
添加(changeButtonsButton,0,0);
changebuttonexts();
添加(buttonGrid,1,0);
场景=新场景(bgGrid,440140);
初级阶段。场景(场景);
primaryStage.show();
}
public void updateButtonsGrid(){
buttonGrid=新建网格窗格();
对于(int i=0;i如何显示?
}
public void changebuttonexts(){
buttonexts.clear();
随机=新随机();
int buttonCount=random.nextInt(15)+10;
对于(int i=0;i
或者有比使用
网格窗格更好的选项吗?使用列表视图
和可观察列表
会起作用,但是按钮不会以表格形式显示,每行有五个按钮。创建一个新的网格窗格
。在函数updateButtonsGrid
中,更改行
buttonGrid = new GridPane();
到
如果出于某种原因,您绝对确定需要GridPane
的新实例,请从bgGrid
中删除旧实例,然后添加新实例。在当前的代码示例中,GridPane
的新实例从未添加到场景图中。创建新的GridPane
可能不是您想要的。在函数updateButtonsGrid
中,更改行
buttonGrid = new GridPane();
到
如果出于某种原因,您绝对确定需要GridPane
的新实例,请从bgGrid
中删除旧实例,然后添加新实例。在当前的代码示例中,GridPane
的新实例从未添加到场景图中。为什么要创建一个新的GridPane
,而不是使用场景中的实例?这可能是您的问题…为什么要创建一个新的网格窗格
,而不是使用场景中的网格窗格?这可能是你的问题。。。