Javafx:按钮处理程序中的按钮处理程序
问题描述:
Button a=new Button();
...
a.setOnAction(new EventHandler<ActionEvent>()
{
public void handle(ActionEvent e)
{
Button []b=new Button();
...
}
});
单击按钮a后,其他按钮b将显示出来。我想为按钮b创建一个事件处理程序。我该怎么办?Javafx:按钮处理程序中的按钮处理程序
答
它被称为动态添加节点(按钮)。你可以用这种方法练习。
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class JavaFXApplication91 extends Application
{
int idControl = 0;
@Override
public void start(Stage primaryStage)
{
VBox root = new VBox();
Button btn = new Button();
btn.setText("Add New Button");
btn.setId("Button " + idControl);
btn.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
idControl++;
Button tempButton = new Button();
tempButton.setText("Button " + idControl);
tempButton.setId("Button " + idControl);
tempButton.setOnAction(new EventHandler<ActionEvent>(){
@Override
public void handle(ActionEvent event2)
{
System.out.println("You clicked: " + ((Button)event2.getSource()).getId());
}
});
root.getChildren().add(tempButton);
}
});
root.getChildren().add(btn);
Scene scene = new Scene(root, 300, 250);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
launch(args);
}
}
此应用程序在启动时创建一个按钮。如果你点击按钮,它会创建一个新的按钮。点击每个新按钮时,显示被点击的按钮的ID。
答
您只需点击Button a
后不必须有一个按钮,处理器内部的按钮处理程序,如果Button b
显示出来,你可以添加另一个Button b
处理器(外Button a
处理程序),如果其不可见Button b
无法不火click事件
我不明白这个问题。完全按照你想要做的事情,并为按钮b创建事件处理程序有什么问题? – Mark
这个问题可能是由于尝试将'Button'实例分配给Button []'数组引起的,编译器会在消息中告诉您编译错误。 – f*