我想在我的自定义组件中得到两个按钮的事件。这个组件是一个图像视图,有两个按钮可以在图像之间移动,但是我需要获得当前显示的图像的位置,我存储图像的键,但是我需要知道什么时候在自定义组件之外按了一个按钮,这样我就可以在自定义组件之外更改标签。
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....
}发布于 2013-11-20 13:07:06
如果我正确理解了你的问题,你想要一个绑定..。遵循以下步骤:
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)将此属性绑定到图片库中的标签文本:
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".
}
});https://stackoverflow.com/questions/20081330
复制相似问题