是否有可能注入ImageView
个对象的数组?
或者一些类似的方法来减少代码行数量?
所以这就是我的意思:
@FXML
private ImageView led;
@FXML
private ImageView led1;
...
@FXML
private ImageView led64;
是否有像
这样的东西@FXML
private ImageViewArray led[64];
我只想减少我必须写的行数'因为我需要很多这些ImageView对象,我必须初始化它们。 (也许有更好的方法可以做到这一点,所以请提出一些有用的方法)
以下是完整代码:
public class guiController implements Initializable {
private static final Image ledOff = new Image("/images/led_white.gif");
private static final Image ledOn = new Image("/images/led_blue.gif");
@FXML
private ImageView led;
@FXML
private ImageView led1;
@FXML
private ImageView led2;
@FXML
private ImageView led3;
@FXML
private ImageView led4;
@FXML
private ImageView led5;
@FXML
private ImageView led6;
@FXML
private ImageView led7;
@FXML
private void handleLedAction(MouseEvent ev){
ImageView led = (ImageView) ev.getSource();
if(led.getImage().equals(ledOff)){
led.setImage(ledOn);
} else{
led.setImage(ledOff);
}
}
@Override
public void initialize(URL url, ResourceBundle rb) {
led.setImage(ledOff);
led1.setImage(ledOff);
led2.setImage(ledOff);
led3.setImage(ledOff);
led4.setImage(ledOff);
led5.setImage(ledOff);
led6.setImage(ledOff);
led7.setImage(ledOff);
}
}
答案 0 :(得分:2)
如果您有那么多控件,那么用Java而不是FXML创建它们可能会更好。您可以创建要在FXML文件中保存它们的容器,然后只需在控制器的ImageView
方法中将initialize
添加到它们中。
例如,在FXML中你可以做到
<GridPane fx:id="ledPanel" />
然后在控制器中
private static final Image ledOff = new Image("/images/led_white.gif");
private static final Image ledOn = new Image("/images/led_blue.gif");
@FXML
private GridPane ledPanel ;
private ImageView[] leds ;
public void initialize() {
final int numLeds = 64 ;
final int numLedsPerRow = 8 ;
leds = new ImageView[numLeds];
for (int i=0; i<numLeds; i++) {
ImageView led = new ImageView(ledOff);
leds[i] = led ;
ledPanel.add(leds[i], i % numLedsPerRow, i / numLedsPerRow);
led.setOnMousePressed(event -> {
if (led.getImage()==ledOff) {
led.setImage(ledOn);
} else {
led.setImage(ledOff);
}
});
}
}
(顺便说一下,因为看起来这些是您通过鼠标点击打开和关闭的项目,您可能更愿意使用RadioButton
或CheckBox
而不是ImageView
s,只需使用CSS来配置它们对图像的外观。这样就可以获得所有事件处理和已编码的选定状态。)