【问题标题】:EventHandler and Rectangle JavaFxEventHandler 和矩形 JavaFx
【发布时间】:2021-10-22 21:22:41
【问题描述】:
  • 我不想使用匿名类。
  • 如何更改/使用我的 EventHandler 上的记录?

颜色开关类:

public class FarbtestEventHandlerAusserhalb extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Pane p = new Pane();
        BorderPane bp = new BorderPane();
        bp.setPadding(new Insets(10.0, 20.0, 10.0, 10.0));
        Rectangle rec = new Rectangle(150.0, 50.0, 100.0, 100.0);
        p.getChildren().add(rec);
        rec.setFill(Color.BLUE);
        
        Button btn = new Button("Farbenwechsel");
        btn.setOnAction(new MyEventHandler());
        
        bp.setCenter(rec);
        bp.setBottom(btn);
        BorderPane.setAlignment(btn, Pos.CENTER);
        
        Scene scene = new Scene(bp, 300.0, 280);
        primaryStage.setTitle("Farb-Test");
        primaryStage.setScene(scene);
        primaryStage.show();
        
        
    }
    
    public static void main(String[] args) {
        launch();
    }

}


MyEvendHandler 类

import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.paint.Color;

public class MyEventHandler implements EventHandler<ActionEvent>{
    public void handle(ActionEvent e)
    {
        int rot = (int) (Math.random() * 255.0);
        int gruen = (int) (Math.random() * 255.0);
        int blau = (int) (Math.random() * 255.0);
        FarbtestEventHandlerAusserhalb feha = new FarbtestEventHandlerAusserhalb();
        rec.setFill(Color.rgb(rot, gruen, blau));
    }
}
  • 来自 Eclipse 的错误:rec 无法解决
  • 我想用recto改变颜色

【问题讨论】:

    标签: javafx-8


    【解决方案1】:

    因为,MyEventHandler() 不知道“rec”。 MyeventHandler 类应该如下,

    public class MyEventHandler implements EventHandler<ActionEvent>{
    
    Rectangle  rec;
    
    public MyEventHandler(Rectangle rec) {
        
        this.rec = rec;
        
    }
    
    public void handle(ActionEvent e)
    {
        int rot = (int) (Math.random() * 255.0);
        int gruen = (int) (Math.random() * 255.0);
        int blau = (int) (Math.random() * 255.0);
        FarbtestEventHandlerAusserhalb feha = new FarbtestEventHandlerAusserhalb();
        rec.setFill(Color.rgb(rot, gruen, blau));
    }
    }
    

    用法:

     btn.setOnAction(new MyEventHandler(rec));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多