java点击menuitem打开另一个类
时间: 2023-07-29 07:14:03 浏览: 108
要实现在Java中点击MenuItem打开另一个类的窗口,可以按照以下步骤进行:
1. 创建一个MenuItem对象,并添加到Menu中:
```
MenuItem menuItem = new MenuItem("Open Another Window");
Menu menu = new Menu("File");
menu.getItems().add(menuItem);
```
2. 给MenuItem添加事件监听器,当MenuItem被点击时,创建另一个类的实例并显示:
```
menuItem.setOnAction(event -> {
AnotherWindow anotherWindow = new AnotherWindow();
anotherWindow.show();
});
```
3. 创建另一个类,继承自Stage,并实现其构造方法和需要的界面元素:
```
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class AnotherWindow extends Stage {
public AnotherWindow() {
VBox root = new VBox();
root.getChildren().add(new Label("This is another window!"));
Scene scene = new Scene(root, 400, 300);
setScene(scene);
}
}
```
完整代码示例:
```
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuBar;
import javafx.scene.control.MenuItem;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class Main extends Application {
@Override
public void start(Stage primaryStage) throws Exception{
MenuItem menuItem = new MenuItem("Open Another Window");
menuItem.setOnAction(event -> {
AnotherWindow anotherWindow = new AnotherWindow();
anotherWindow.show();
});
Menu menu = new Menu("File");
menu.getItems().add(menuItem);
MenuBar menuBar = new MenuBar();
menuBar.getMenus().add(menu);
VBox root = new VBox();
root.getChildren().add(menuBar);
Scene scene = new Scene(root, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
class AnotherWindow extends Stage {
public AnotherWindow() {
VBox root = new VBox();
root.getChildren().add(new Label("This is another window!"));
Scene scene = new Scene(root, 400, 300);
setScene(scene);
}
}
```
运行程序,点击菜单栏中的“File” -> “Open Another Window”即可打开另一个类的窗口。
阅读全文
相关推荐


















