当使用 for 循环将菜单项添加到“连接”菜单时,我在 InteliJ IDEA 中收到以下错误:
无法将 javafx.scene.control.Menu 设置为字段“menuConnection”
我认为这是由某种命名冲突引起的。对于 Java 来说还很陌生,所以不能确定。
这是我的 FXML 文件:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<VBox xmlns="http://javafx.com/javafx"
xmlns:fx="http://javafx.com/fxml"
fx:controller="kuristo.Controller"
prefHeight="400.0" prefWidth="600.0">
<MenuBar>
<Menu text="File">
<MenuItem text="Quit" />
</Menu>
<Menu text="Connection" fx:id="menuConnection"></Menu>
</MenuBar>
</VBox>
正如您在该文件中看到的,我有一个 ID 为 menuConnection 的菜单。我使用它作为识别我希望在此 Controller 中添加 MenuItems 的菜单的方法:
package kuristo;
import com.fazecast.jSerialComm.SerialPort;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import java.awt.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
private Menu menuConnection;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
for (int i = 0; i < SerialPort.getCommPorts().length; i++) {
// String portName = "portName".concat(String.valueOf(i));
MenuItem port = new MenuItem(SerialPort.getCommPorts()[i].getSystemPortName());
menuConnection.add(port);
}
}
}
我无法编译它。任何帮助将不胜感激。
干杯,
最佳答案
事实证明...
我的导入不正确。
import java.awt.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.ResourceBundle;
更改为:
import com.fazecast.jSerialComm.SerialPort;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import java.net.URL;
import java.util.ResourceBundle;
这里的故事告诉我们,确保您使用的是 JavaFX 而不是 AWT。
关于java - 如何在 JavaFX 中使用菜单栏中的 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55893401/