【发布时间】:2014-11-18 16:34:56
【问题描述】:
我正在尝试在 JavaFX 中创建一个工具栏,以使用 FXML 添加按钮,如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.net.*?
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import com.supridatta.javafx.*?>
<BorderPane xmlns:fx="http://javafx.com/fxml/1" prefHeight="200" prefWidth="320" fx:controller="com.supridatta.javafx.MainController">
<stylesheets>
<URL value="@main.css"/>
</stylesheets>
<top>
<com.supridatta.javafx.ButtonBar fx:id="buttonBar">
<buttons>
<ButtonBarButton path="/com/supridatta/javafx/icons/plus.png"/>
<ButtonBarButton path="/com/supridatta/javafx/icons/minus.png"/>
<ButtonBarButton path="/com/supridatta/javafx/icons/last.png"/>
</buttons>
</com.supridatta.javafx.ButtonBar>
</top>
<bottom>
<Button text="Exibir todos" onAction="#showAllButtons"/>
</bottom>
</BorderPane>
下面是对应的java类:
package com.supridatta.javafx;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
public class ButtonBar extends StackPane {
private final HBox contentPane = new HBox();
private final ObservableList<ButtonBarButton> buttons = FXCollections.observableArrayList();
public ButtonBar() {
initButtonBar();
}
private void initButtonBar() {
getChildren().add(contentPane);
setAlignment(Pos.CENTER);
buttons.addListener(new ListChangeListener<Node>() {
@Override
public void onChanged(ListChangeListener.Change<? extends Node> c) {
while (c.next()) {
if (c.wasAdded()) {
for (Node node : c.getAddedSubList()) {
contentPane.getChildren().add(node);
}
}
if (c.wasRemoved()) {
for (Node node : c.getAddedSubList()) {
contentPane.getChildren().remove(node);
}
}
}
}
});
}
public void setButtons(ObservableList<ButtonBarButton> contents) {
this.buttons.setAll(contents);
}
public ObservableList<ButtonBarButton> getButtons() {
return buttons;
}
public void addButton(ButtonBarButton button) {
buttons.add(button);
}
public void removeButton(ButtonBarButton button) {
buttons.remove(button);
}
}
当我运行项目时,我遇到了这个异常:
java.lang.IllegalArgumentException: Unable to coerce ButtonBarButton@2fd0ac8f[styleClass=button ButtonBarButton]'' to
interface javafx.collections.ObservableList.
提前致谢。
【问题讨论】:
标签: java javafx custom-controls fxml