JavaFX - problems and solutions (updated from time to time)

Let me make a complaint~ It is said that JavaFX is better than Swing. The native UI is good-looking, and the separation of design and code looks comfortable, but why is there so little useful information on the Internet, and why some UI designs have to be explained in the code. Just thinking about it gives me a headache. The following are questions that I can't find answers to on the Internet when I use JavaFX. I hope to help those who encounter the same problem.

Question 1: 

There is obviously no gap in the page of JavaFX Scene Builder, but there is a gap when it is actually running, and it is useless to design it. General components are fine, they need to leave space with the border, but what do you want to leave such a large blank space for the menu bar (Menu)? !

 Solution:

It can only be solved by code.  First set fx:id=menu for the menu bar in FXML , and then set its scope to public  in the controller (MenuController)

@FXML
public MenuBar menu;    // 方便后面的调用

 Finally, set the width of the menu at the beginning of the layout call:

javafx.fxml.FXMLLoader loader = new javafx.fxml.FXMLLoader(getClass().getResource("ui/Menu.fxml"));
stage.show();    // 先显示再设置。根据显示的实际宽度进行设置的
// 将菜单栏的宽度设置为与窗体宽度相等,间隙就没有了
((MenuController)loader.getController()).menu.setPrefWidth(stage.getWidth());

Question 2:

The way to set menu (Menu) and menu item (MenuItem) icons on the Internet is through code. In fact, you can set the icon through the graphic tag in FXML (the picture size is preferably 16x16):

  <Menu mnemonicParsing="false" text="更新">
    <graphic>
        <ImageView>
            <Image url="@img/update.png" />
        </ImageView>
    </graphic>
    <items>
        <MenuItem mnemonicParsing="false" onAction="#update" text="项目">
           <graphic>
                <ImageView>
                    <Image url="@img/project.png" />
                </ImageView>
           </graphic>
        </MenuItem>
        <SeparatorMenuItem mnemonicParsing="false" />
        <MenuItem mnemonicParsing="false" onAction="#update" text="模块" >
            <graphic>
                <ImageView>
                    <Image url="@img/module.png" />
                </ImageView>
            </graphic>
        </MenuItem>
    </items>
  </Menu>

Renderings:

 

Guess you like

Origin blog.csdn.net/qq_30917141/article/details/129623850