简体   繁体   English

javafx-单独的EventHandler和gui代码

[英]javafx - Separate EventHandler and gui code

So i would like to know how i can separate Events in a class and have the GUI code in another class without them having direct knowledge of eachother. 因此,我想知道如何在一个类中将事件分开,而又将GUI代码放在另一个类中,而又无需彼此直接了解。 I have recently only been working in one class , where i have been putting GUI code and listeners in the start method. 最近,我只在一个类中工作,在该类中,我一直在start方法中放置GUI代码和侦听器。

this is what iv'e done so far but the button dosen't work: 到目前为止,这是我所做的,但是按钮不起作用:

GUI class: GUI类:

package application;

import javafx.application.Application;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.BorderPane;


public class GUI extends Application {

Button btn1 = new Button("press me");

@Override
public void start(Stage primaryStage) {
    try {
        BorderPane root = new BorderPane();
        Scene scene = new Scene(root,400,400);

        root.setCenter(btn1);
        primaryStage.setScene(scene);
        primaryStage.show();


       } catch(Exception e) {

        e.printStackTrace();
        }
    }


}

Controller class: 控制器类:

package application;

import javafx.event.Event;
import javafx.event.EventHandler;

public class Control implements EventHandler<Event>{

GUI gui;

public Control(GUI gui) {
    this.gui = gui;
}

@Override
public void handle(Event event) {
    Object cmd = event.getSource();
    if(gui.btn1.equals(cmd)){
        System.out.println("your pressed btn1");
      }
   }

}

Main class: 主班:

package application;

public class Main extends GUI {

public static void main(String[] args) {
    launch(args);

    GUI gui = new GUI();
    Control control = new Control(gui);
   }
}

将控件类设置为按钮的事件处理程序。

button.setOnAction(new Control(this )) ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM