Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
JavaFX Listview将按钮绑定到单元格的索引_Java_Listview_Javafx_Custom Cell - Fatal编程技术网

JavaFX Listview将按钮绑定到单元格的索引

JavaFX Listview将按钮绑定到单元格的索引,java,listview,javafx,custom-cell,Java,Listview,Javafx,Custom Cell,我试图用JavaFX构建一个自定义视图,允许在单元格中放置两个按钮“编辑用户”和“查看用户” 我已经构建了适配器,但是在创建单元格时,我很难将索引分配给按钮,这是一个问题,因为当我单击单元格中的按钮时,会得到一个空指针 《编辑》2014年4月7日:我更新了一点程序逻辑,但我仍在努力找到解决问题的方法-分配的索引有时是正确的,但大部分是不正确的(我建立了一个日志,给我提供当前索引,它剧烈波动,这使我得出结论,我的单元格构造函数不可靠) 我现在使用以下代码:populateListView(): p

我试图用JavaFX构建一个自定义视图,允许在单元格中放置两个按钮“编辑用户”和“查看用户”

我已经构建了适配器,但是在创建单元格时,我很难将索引分配给按钮,这是一个问题,因为当我单击单元格中的按钮时,会得到一个空指针

《编辑》2014年4月7日:我更新了一点程序逻辑,但我仍在努力找到解决问题的方法-分配的索引有时是正确的,但大部分是不正确的(我建立了一个日志,给我提供当前索引,它剧烈波动,这使我得出结论,我的单元格构造函数不可靠)

我现在使用以下代码:populateListView():

public void populateListView(){
//每次重新填充列表视图时,将索引归零
//绑定到正确的按钮
指数=0;
//将列表内容刷新为空
lstNotes.setItems(空);
//包含要添加的项目的可观察列表
ObservableList notes=populateObservable(thisTenant.getNotes());
//设置populateObservable返回的项目(T);
lstNotes.设置项目(注释);
lstNotes.设置固定单元大小(50);
//使用单元工厂进行自定义样式设置
lstNotes.setCellFactory(新回调(){
@凌驾
公共ListCell调用(ListView ListView){
NoteCell nCell=新的NoteCell(索引、控制器);
索引++;
nCell.getStyleClass().add(“边框底部”);
返回nCell;
}
});
}
这里的注释是不言自明的-通过此方法填充可观察项列表-populateObservable(NoteList n):

公共可观察列表populateObservable(ArrayList notesArray){
ObservableList notes=FXCollections.observableArrayList();
//循环浏览users Notes数组并创建listview项
对于(int i=0;i
最后,自定义视图是在我的单元格工厂中构建的(样式与问题无关),需要注意的是将对控制器的引用传递给它,以便我可以访问方法-在NoteCell类中,我有一个方法来删除给定索引处的行(这就是产生扭曲结果的原因)

cross.setOnMouseClicked(新的EventHandler(){
@凌驾
公共无效句柄(MouseEvent MouseEvent){
ScreensFramework.logGeneral.writeToFile(“我正在从索引中删除”+String.valueOf(thisIndex));
if(thisTenant.removeNoteAt(thisIndex,true)){
controller.populateListView();
}否则{
controller.populateListView();
}
}
});
对populateListView()的调用只是为了刷新listview的内容,并根据租户的更新注释数组重新构建它

RemoveNoteAt()方法向我的db发送一个删除查询,并从给定索引处的租户注释数组中删除注释(但我并不总是像上面所说的那样获得正确的索引,因为我找不到有效的方法将按钮绑定到ListViews单元格,而且我传递索引的微弱尝试似乎不起作用)

我希望这次更新能为我的问题提供一个更清晰的范围,如果您需要更多信息来更清楚地理解这一点,请询问

编辑:NoteCell代码:

public class NoteCell extends ListCell<String> {
HBox hbox = new HBox();
HBox c = new HBox();
Pane b = new HBox();
Pane pane = new Pane();
Label msg = new Label();
Label date = new Label();
Button cross = new Button();
Tenant thisTenant;
int thisIndex;

String lastItem;


public NoteCell(int index, UserInfoController controller) {
    super();

    try{
        thisTenant = controller.getTenant();
        Note currNote = thisTenant.getNoteAt(index);
        date = new Label(currNote.getDate());
        System.out.println(thisTenant.getNotes());
        thisIndex = index;

        date.setStyle("-fx-text-fill: #fff !important; -fx-font-family: Helvetica; -fx-font-weight: bold; -fx-font-size: 12px; -fx-background-color: #f9246b; -fx-border-color: #FE246C; -fx-padding: 8 8 6 8; -fx-border-radius: 6; -fx-background-radius: 6");
        b.setStyle("-fx-padding: 10px 5px 10px 5px");
        msg.setStyle("-fx-text-fill: #fafafa; -fx-font-size: 14px; -fx-font-family: 'Open Sans Light'; -fx-label-padding: 10px");
        cross.getStyleClass().add("button_close");
        cross.setTranslateY(20);
        msg.setAlignment(Pos.CENTER_LEFT);

        pane.setTranslateY(20);
        b.getChildren().add(date);
        c.getChildren().add(cross);
        hbox.getChildren().addAll(b, msg, pane, cross);
        HBox.setHgrow(pane, Priority.ALWAYS);


        // Deletes the note
        cross.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                ScreensFramework.logGeneral.writeToFile("I am removing from index " + String.valueOf(thisIndex));
                if(thisTenant.removeNoteAt(thisIndex, true)){
                    controller.populateListView();
                } else {
                    controller.populateListView();
                }
            }
        });

    } catch (Exception e) {
        ScreensFramework.logError.writeToFile(e.getMessage());
    }
}



@Override
protected void updateItem(String item, boolean empty) {

    super.updateItem(item, empty);
    setText(null);  // No text in label of super class
    if (empty) {
        lastItem = null;
        setGraphic(null);
    } else {
        lastItem = item;
        msg.setText(item!=null ? item : "<null>");
        setGraphic(hbox);
    }
}
public类NoteCell扩展了ListCell{
HBox HBox=新的HBox();
HBox c=新的HBox();
窗格b=新的HBox();
窗格=新窗格();
Label msg=新标签();
标签日期=新标签();
按钮交叉=新按钮();
承租人该承租人;
int这个索引;
字符串最后一项;
公共NoteCell(int索引,UserInfoController){
超级();
试一试{
thisTenant=controller.getTenant();
Note currNote=thisTenant.getNoteAt(索引);
日期=新标签(currNote.getDate());
System.out.println(thisttenant.getNotes());
该指数=指数;
date.setStyle(“-fx文本填充:#fff!重要;-fx字体系列:Helvetica;-fx字体重量:粗体;-fx字体大小:12px;-fx背景颜色:#f9246b;-fx边框颜色:#FE246C;-fx填充:8;-fx边框半径:6;-fx背景半径:6”);
b、 设置样式(“-fx填充:10px 5px 10px 5px”);
msg.setStyle(“-fx文本填充:#fafafafa;-fx字体大小:14px;-fx字体系列:'opensans Light';-fx标签填充:10px”);
cross.getStyleClass().add(“按钮关闭”);
克罗斯·塞特兰泰(20);
msg.setAlignment(位置中心左);
窗格。setTranslateY(20);
b、 getChildren().add(日期);
c、 getChildren().add(交叉);
hbox.getChildren().addAll(b,msg,pane,cross);
HBox.setHgrow(窗格,Priority.ALWAYS);
//删除注释
cross.setOnMouseClicked(新的EventHandler(){
@凌驾
公共无效句柄(MouseEvent MouseEvent){
ScreensFramework.logGeneral.writeToFile(“我正在从索引中删除”+String.valueOf(thisIndex));
if(thisTenant.removeNoteAt(thisIndex,true)){
controller.populateListView();
}否则{
controller.populateListView();
}
}
});
}捕获(例外e){
ScreensFramework.logError.writeToFile(e.getMessage());
}
}
@凌驾
受保护的void updateItem(字符串项,布尔值为空){
super.updateItem(项,空);
setText(null);//超类的标签中没有文本
if(空){
lastItem=null;
设置图形(空);
}否则{
lastItem=项目;
msg.setText(项!=null?项:“”);
设置图形(hbox);
}
}
}

编辑:在创建ListView单元格时,有没有办法将该单元格的当前索引传递给“CellFactory”

问候,, 亚历克斯

每个行政长官
public ObservableList populateObservable(ArrayList<Note> notesArray) {

    ObservableList notes = FXCollections.observableArrayList();

    // Loop through the users Notes array and create a listview item
    for(int i = 0; i < notesArray.size(); i++) {
        Note thisNote = notesArray.get(i);
        notes.add(thisNote.getMessage());
    }

    return notes;
}
 cross.setOnMouseClicked(new EventHandler<MouseEvent>() {
      @Override
      public void handle(MouseEvent mouseEvent) {
          ScreensFramework.logGeneral.writeToFile("I am removing from index " + String.valueOf(thisIndex));
          if(thisTenant.removeNoteAt(thisIndex, true)){
              controller.populateListView();
          } else {
              controller.populateListView();
          }
      }
  });
public class NoteCell extends ListCell<String> {
HBox hbox = new HBox();
HBox c = new HBox();
Pane b = new HBox();
Pane pane = new Pane();
Label msg = new Label();
Label date = new Label();
Button cross = new Button();
Tenant thisTenant;
int thisIndex;

String lastItem;


public NoteCell(int index, UserInfoController controller) {
    super();

    try{
        thisTenant = controller.getTenant();
        Note currNote = thisTenant.getNoteAt(index);
        date = new Label(currNote.getDate());
        System.out.println(thisTenant.getNotes());
        thisIndex = index;

        date.setStyle("-fx-text-fill: #fff !important; -fx-font-family: Helvetica; -fx-font-weight: bold; -fx-font-size: 12px; -fx-background-color: #f9246b; -fx-border-color: #FE246C; -fx-padding: 8 8 6 8; -fx-border-radius: 6; -fx-background-radius: 6");
        b.setStyle("-fx-padding: 10px 5px 10px 5px");
        msg.setStyle("-fx-text-fill: #fafafa; -fx-font-size: 14px; -fx-font-family: 'Open Sans Light'; -fx-label-padding: 10px");
        cross.getStyleClass().add("button_close");
        cross.setTranslateY(20);
        msg.setAlignment(Pos.CENTER_LEFT);

        pane.setTranslateY(20);
        b.getChildren().add(date);
        c.getChildren().add(cross);
        hbox.getChildren().addAll(b, msg, pane, cross);
        HBox.setHgrow(pane, Priority.ALWAYS);


        // Deletes the note
        cross.setOnMouseClicked(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent mouseEvent) {
                ScreensFramework.logGeneral.writeToFile("I am removing from index " + String.valueOf(thisIndex));
                if(thisTenant.removeNoteAt(thisIndex, true)){
                    controller.populateListView();
                } else {
                    controller.populateListView();
                }
            }
        });

    } catch (Exception e) {
        ScreensFramework.logError.writeToFile(e.getMessage());
    }
}



@Override
protected void updateItem(String item, boolean empty) {

    super.updateItem(item, empty);
    setText(null);  // No text in label of super class
    if (empty) {
        lastItem = null;
        setGraphic(null);
    } else {
        lastItem = item;
        msg.setText(item!=null ? item : "<null>");
        setGraphic(hbox);
    }
}
public class Demo extends Application {

    ListView<String> list = new ListView<String>();

    ObservableList<String> data = FXCollections.observableArrayList(
            "chocolate", "salmon", "gold", "coral", "darkorchid",
            "darkgoldenrod", "lightsalmon", "black", "rosybrown", "blue",
            "blueviolet", "brown");

    @Override
    public void start(Stage stage) {
        VBox box = new VBox();
        Scene scene = new Scene(box, 200, 200);
        stage.setScene(scene);
        box.getChildren().addAll(list);
        VBox.setVgrow(list, Priority.ALWAYS);

        list.setItems(data);

        list.setCellFactory(new Callback<ListView<String>, ListCell<String>>() {
            @Override
            public ListCell<String> call(ListView<String> list) {
                return new ButtonCell();
            }
        });
        stage.show();
    }

    static class ButtonCell extends ListCell<String> {
        @Override
        public void updateItem(String item, boolean empty) {
            super.updateItem(item, empty);
            if (item != null) {
                final Button btn = new Button(item + " with index " + getIndex());
                btn.setOnAction(new EventHandler<ActionEvent>() {
                    @Override
                    public void handle(ActionEvent event) {
                        System.out.println("I am a " + getItem() + " with index " + getIndex());
                    }
                });
                setGraphic(btn);
            } else {
                setGraphic(null);
            }
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}