26

ユーザーがListView要素の項目をクリックした後、何らかのアクションを実行する必要があるJavaFX2.0アプリケーションがあります。ユーザーGUIを構築するために、私はFXMLを使用しています。ここでは、次のようなものがあります。

        <children>
            <ListView fx:id="listView" GridPane.columnIndex="0" 
            GridPane.rowIndex="1" labelFor="$pane" 
            onPropertyChange="#handleListViewAction"/>
        </children>

そして、これが私がこのイベントのためにコントローラーに持っているものです:

        @FXML protected void handleListViewAction(ActionEvent event) {
           System.out.println("OK");
        }

そして、このGUIのシーンが構築されたときに、エラーが発生します。

javafx.fxml.LoadException: java.lang.String does not define a property model for "property".
at javafx.fxml.FXMLLoader$Element.processEventHandlerAttributes(Unknown Source)
at javafx.fxml.FXMLLoader$ValueElement.processEndElement(Unknown Source)
at javafx.fxml.FXMLLoader.processEndElement(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at javafx.fxml.FXMLLoader.load(Unknown Source)
at fxmlexample.FXMLExampleController.handleSubmitButtonAction(FXMLExampleController.java:49)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Node.fireEvent(Unknown Source)
at javafx.scene.control.Button.fire(Unknown Source)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(Unknown Source)
at com.sun.javafx.scene.control.skin.SkinBase$5.handle(Unknown Source)
at com.sun.javafx.scene.control.skin.SkinBase$5.handle(Unknown Source)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEventImpl(Unknown Source)
at com.sun.javafx.event.EventUtil.fireEvent(Unknown Source)
at javafx.event.Event.fireEvent(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.process(Unknown Source)
at javafx.scene.Scene$MouseHandler.access$1300(Unknown Source)
at javafx.scene.Scene.impl_processMouseEvent(Unknown Source)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Unknown Source)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.handleMouseEvent(Unknown Source)
at com.sun.glass.ui.View.notifyMouse(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source)
at com.sun.glass.ui.win.WinApplication$2$1.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722) java.lang.NullPointerException
at javafx.scene.Scene.doCSSPass(Unknown Source)
at javafx.scene.Scene.access$2900(Unknown Source)
at javafx.scene.Scene$ScenePulseListener.pulse(Unknown Source)
at com.sun.javafx.tk.Toolkit.firePulse(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit.pulse(Unknown Source)
at com.sun.javafx.tk.quantum.QuantumToolkit$8.run(Unknown Source)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(Unknown Source)
at com.sun.glass.ui.win.WinApplication$2$1.run(Unknown Source)
at java.lang.Thread.run(Thread.java:722)

そして、この例外の最後のブロック(ここからjava.lang.NullPointerException)がループされます。

4

5 に答える 5

51

FXMLの属性と値はFXAPIに直接マッピングされます。したがって、ハンドラーの記述方法を見つけるには、最初にAPIによって必要なエンティティを作成できます。

マウスクリック時にListView要素にアクションを追加したいようですので、マウスクリックハンドラーを追加する必要があります。APIでは、次のように見えます。

    final ListView lv = new ListView(FXCollections.observableList(Arrays.asList("one", "2", "3")));
    lv.setOnMouseClicked(new EventHandler<MouseEvent>() {

        @Override
        public void handle(MouseEvent event) {
            System.out.println("clicked on " + lv.getSelectionModel().getSelectedItem());
        }
    });

そのコードを見ると、FXMLで属性をオーバーライドする必要があるものを見つけることができますonMouseClicked

<ListView fx:id="listView" onMouseClicked="#handleMouseClick"/>

MouseEventまた、コントローラーでは、ハンドラーにパラメーターを提供する必要があります。

@FXML
private ListView listView;

@FXML public void handleMouseClick(MouseEvent arg0) {
    System.out.println("clicked on " + listView.getSelectionModel().getSelectedItem());
}
于 2012-03-15T18:58:59.240 に答える
9

@SergeyGrinevからの回答に問題がある可能性があります。ListViewが十分にいっぱいになっていない場合、つまり、空白が含まれている可能性があります。次に、空白スペースを気に入っても、選択範囲が変更されることはありません。 ここに画像の説明を入力してください

解決策:カスタムListCellを使用します。

  1. カスタムクラスを定義すると、ListCellが拡張されます。
  2. updateItem関数では、アイテムクリックイベントハンドラーをセルルートノードに設定できます。

持っているアイテムの数がわからない場合。あなたはそうするだけではありません。あなたはスペースのために時間を使うべきです。

Demostrate:

ListViewコードセグメント内:

listView.setCellFactory(new AppListCellFactory());

AppListCellFactory.java:

パブリッククラスAppListCellFactoryは、Callback、ListCell>{を実装します

// only one global event handler private EventHandler<MouseEvent> oneClickHandler; public AppListCellFactory(){ oneClickHandler = new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { Parent p = (Parent) event.getSource(); // do what you want to do with data. AppClickHandler.onAppBeanClicked((AppBean) p.getUserData()); } }; } @Override public ListCell<AppBean> call(ListView<AppBean> param) { return new DemoListCell(oneClickHandler); } public static final class DemoListCell extends ListCell<AppBean> { private EventHandler<MouseEvent> clickHandler; /** * This is ListView item root node. */ private Parent itemRoot; private Label label_AppName; private ImageView imgv_AppIcon; DemoListCell(EventHandler<MouseEvent> clickHandler) { this.clickHandler = clickHandler; } @Override protected void updateItem(AppBean app, boolean empty) { super.updateItem(app, empty); if (app == null) { setText(null); setGraphic(null); return; } if (null == itemRoot) { try { itemRoot = FXMLLoader.load(getClass().getResource(("fxml/appList_item.fxml"))); } catch (IOException e) { throw new RuntimeException(e); } label_AppName = (Label) itemRoot.lookup("#item_Label_AppName"); imgv_AppIcon = (ImageView) itemRoot.lookup("#item_ImageView_AppIcon"); itemRoot.setOnMouseClicked(clickHandler); } // set user data. like android's setTag(Object). itemRoot.setUserData(app); label_AppName.setText(app.name); imgv_AppIcon.setImage(new Image(getClass().getResource("img/icon_64.png").toExternalForm())); setGraphic(itemRoot); } }

}

于 2014-04-17T06:47:36.367 に答える
5

空白スペースで不要なイベントを消費することもできます。

call()セルファクトリの追加:

cell.setOnMousePressed((MouseEvent event) -> {
    if (cell.isEmpty()) {
       event.consume();
    }
});

これも無効になりclickますdragStart

私のプロジェクトのcellFactory全体の例:

public static Callback<ListView<BlockFactory>, ListCell<BlockFactory>> getCellFactory() {
    return new Callback<ListView<BlockFactory>, ListCell<BlockFactory>>() {

        @Override
        public ListCell<BlockFactory> call(ListView<BlockFactory> param) {
            ListCell<BlockFactory> cell = new ListCell<BlockFactory>() {

                @Override
                protected void updateItem(BlockFactory item, boolean empty) {
                    super.updateItem(item, empty);
                    if (item != null) {
                        ImageView img = new ImageView(item.img);
                        Label label = new Label(item.desc);
                        HBox bar = new HBox(img, label);
                        bar.setSpacing(15);
                        bar.setAlignment(Pos.CENTER_LEFT);
                        setGraphic(bar);
                    }
                }
            };
            cell.setOnMousePressed((MouseEvent event) -> {
                if (cell.isEmpty()) {
                    event.consume();
                }
            });
            return cell;
        }
    };
}
于 2014-11-03T22:24:49.987 に答える
2

まったく新しいlistCellを作成する必要がない、Sergeyの回答に対する簡単な修正(あなたの場合は作成しますが、通常のテキストの場合は作成する必要はありません)。

単純に行う必要があるのは、最初に最初のリストアイテムに等しい一時変数を作成し、それが新しいクリックされたアイテムごとに変更されることです。アイテムをもう一度クリックしようとすると、一時変数はそれが同じであることを認識し、ifステートメントを使用してそれを回避できます。

一時的なアイテムはあなたがトップに立てたグローバルです String tempItem = "admin";

私にとって、最初のフィールドには常に「admin」というラベルが付けられることを知っていたので、そのように設定しました。最初のエントリを取得して、リストの選択に使用するメソッドの外に設定する必要があります。

private void selUser() throws IOException
    {
    String item = userList.getSelectionModel().getSelectedItem().toString();

        if(item != tempItem)
        {
           //click, do something
        }

        tempItem = item;    
}

私は自分のメソッドを呼び出すFXMLドキュメントを使用しました

@FXML 
public void userSel(MouseEvent mouse) throws IOException
{
selUser();

}

この場合、selUser()メソッドの内容全体を取得して、userSelマウスクリックに入れることができます。

于 2014-09-28T18:27:56.083 に答える
0

古い位置インデックス(リストビューでの検索結果の後)、新しい位置インデックス、値などを取得します。

listView.setOnMouseClicked(me -> {
    System.out.println("clicked on " + listView.getSelectionModel().getSelectedItem());

    int newPosition = listView.getSelectionModel().getSelectedIndex();
    System.out.println("New Position is: " + newPosition);

    String item = listView.getSelectionModel().getSelectedItem();
    int oldPosition = observableMainList.indexOf(item); // the main list which populated the listView 
    System.out.println("Old position is: " + oldPosition);

    String ayahRanges = ayahNumbers.get(oldPosition); // another list which you store some another value 
    System.out.println("Actual AyaRanges: " + ayahRanges);
});
于 2021-09-05T16:33:17.537 に答える