我想在自定义组件中获取两个按钮的事件。 该组件是一个带有两个按钮的图像视图,可以在图像之间移动,但我需要获取当前显示的图像的位置,我存储图像的关键,但我需要知道按钮是否已在按钮外按下组件,所以我可以在自定义组件之外更改标签。
public class TransitionSlider extends AnchorPane {
@FXML
private AnchorPane transitionSliderPane;
@FXML
private ImageView transitionSliderImageView;
@FXML
private Button prevButton;
@FXML
private Button nextButton;
private Map<Integer,Image> imageMap;
private Image currentImage;
private DropShadow imageViewDropShadow;
private int currentKey = 1;
private Image[] images;
public TransitionSlider() {
FXMLLoader loader = new FXMLLoader();
loader.setRoot(this);
loader.setController(this);
loader.setLocation(this.getClass().getResource("TransitionSlider.fxml"));
loader.setClassLoader(this.getClass().getClassLoader());
try {
loader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
prevButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
if(currentKey <= 1){
currentKey = currentKey + 1;
currentImage = imageMap.get(currentKey);
createTransition(transitionSliderImageView, currentImage);
}
}
});
nextButton.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
if(currentKey <= imageMap.size()){
currentKey = currentKey - 1;
currentImage = imageMap.get(currentKey);
createTransition(transitionSliderImageView, currentImage);
}
}
});
}
// more code here...
}
我想要一种方法来捕获事件并在组件中获取变量并在自定义组件外部更改标签......
例如:
public class Gallery extends Application {
@FXML
TransitionSlider ts;
Label label;
@Override
public void start(Stage stage) throws Exception {
label = new Label();
TransitionSlider ts = new TransitionSlider();
ts.captureButtonEvent(){ // need a way to capture this
label.setText(ts.getCurrentKey());
}
// more code here....
}
答案 0 :(得分:1)
如果我理解你的问题,你想要一个绑定..请按照下列步骤操作:
1)将可绑定字段及其getter / setter放入TransitionSlider:
private IntegerProperty currentKey = new SimpleIntegerProperty(1);
public int getCurrentKey() {
return currentKey.get();
}
public void setCurrentKey(int val) {
return currentKey.set(val);
}
public IntegerProperty currentKeyProperty() {
return currentKey;
}
2)将此属性绑定到Gallery中的标签文本:
label = new Label();
TransitionSlider ts = new TransitionSlider();
label.textProperty.bind(ts.currentKeyProperty().asString());
或者,如果您想要做的不仅仅是更改标签的文本,您可以向currentKeyProperty添加更改侦听器:
ts.currentKeyProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable,
Number oldValue, Number newValue) {
label.setText(newValue);
// do other stuff according to "oldValue" and "newValue".
}
});