我怎么可以添加一个听到的每个ListCell创建在我的列表视图1。 获得的数据在该单元和2。 呼叫一个方法吗?

0

的问题

我创建一个模型的一个Java版本的内部数据库对于我的公司。 我成功显示的所有项(在这种情况下,客户)中的列表的观点,但我想要能够调用的方法和获得的数据的单元格。 例如,如果我点击了一个客户的客户ID498,我想要有一些办法访问ID(498),然后显示更多信息对客户的标识。 我可以处理,显示所有信息自己,我只是在努力与如何进入数据的内部细胞。 相关代码:

控制器类的片段,填写的清单查看:

package com.verus.techtracker_2;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.util.Callback;

import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class MainViewController {
ObservableList<ObservableList> data = 
FXCollections.observableArrayList();
@FXML
private Label welcomeText;
@FXML
private ListView<ObservableList> OrgTbl2;
private orgmodel org;
@FXML
private static Connection conn;
private static final String url = "jdbc:sqlserver://10.9.32.46:1433;database=TechTracker;integratedSecurity=true";

public MainViewController() {
}

public static Connection connect() throws SQLException {
    try{
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
    }catch(ClassNotFoundException cnfe){
        System.err.println("Error: "+cnfe.getMessage());
    }catch(InstantiationException ie){
        System.err.println("Error: "+ie.getMessage());
    }catch(IllegalAccessException iae){
        System.err.println("Error: "+iae.getMessage());
    }

    conn = DriverManager.getConnection(url);
    return conn;
}

public static Connection getConnection() throws SQLException, ClassNotFoundException{
    if(conn !=null && !conn.isClosed())
        return conn;
    connect();
    return conn;


}

public void initialize (URL url, ResourceBundle resourceBundle) throws SQLException, ClassNotFoundException {
    loadData();
}
ResultSet rs = null;
public void loadData() throws SQLException, ClassNotFoundException {
    getConnection();


    ObservableList<orgmodel> OrganizationObservableList = FXCollections.observableArrayList();

    try{
        PreparedStatement ps = connect().prepareStatement("SELECT CustomerName,CustomerID, Inactive FROM dbo.tbCustomers");
        rs=ps.executeQuery();
        System.out.println(rs);


        /**
         * ******************************
         * Data added to ObservableList *
         *******************************
         */
        while (rs.next()) {
            //Iterate Row
            ObservableList<String> row = FXCollections.observableArrayList();
            for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
                //Iterate Column
                row.add(rs.getString(i));
            }
            System.out.println("Row [1] added " + row);
            data.add(row);
            org = new orgmodel(rs.getString(1), rs.getString(2), rs.getBoolean(3));
            OrganizationObservableList.add(org);


        }

        //FINALLY ADDED TO TableView
        OrgTbl2.setItems(data);
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error on Building Data");
    }
}


}

设计好的布局文件的文件这样的场景:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.ListView?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.VBox?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="1000.0" prefWidth="1920.0" xmlns="http://javafx.com/javafx/17" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.verus.techtracker_2.MainViewController">
   <children>
      <VBox layoutX="130.0" layoutY="58.0" prefHeight="200.0" prefWidth="100.0" />
      <ListView fx:id="OrgTbl2" layoutX="7.0" layoutY="6.0" onMouseClicked="#loadData" prefHeight="987.0" prefWidth="958.0" />
   </children>
</AnchorPane>

java javafx
2021-11-22 19:53:02
1

最好的答案

2

我认为当你说

例如,如果我点击了一个客户的客户ID的498,

你指的响应,如果用户选择一个项目 ListView. 所有你需要做的就是注册一个监听器的选择,使用

orgTbl2.getSelectionModel().selectedItemProperty().addListener(...)

这会容易得多,如果你让你的 ListView 显示模型的实例,而不是使用 List 代表每一行。 你已经表现出具有一个模型被称为 OrgModel 定义。

这里是一个版本的你的代码这样做。 我已经删除所有不必要的代码,恢复到标准命名的公约,并提出了一些其他的"清洁",以便其他用户可以读取代码很容易。

package com.verus.techtracker_2;

import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.util.Callback;

import java.net.URL;
import java.sql.*;
import java.util.ArrayList;
import java.util.ResourceBundle;

public class MainViewController {

    @FXML
    private Label welcomeText;
    @FXML
    private ListView<OrgModel> orgTbl2;

    private static Connection conn ;
    private static final String url = "jdbc:sqlserver://10.9.32.46:1433;database=TechTracker;integratedSecurity=true";
    
    public void initialize (URL url, ResourceBundle resourceBundle) throws SQLException, ClassNotFoundException {
        loadData();

        orgTbl2.getSelectionModel()
            .selectedItemProperty()
            .addListener((obs, oldSelection, newSelection) -> {

            if (newSelection != null) {
                // assuming names of property accessor methods:
                String customerName = newSelection.getCustomerName();
                String id = newSelection.getId();
                boolean inactive = newSelection.isInactive();
                // do whatever you need with the data:
                System.out.println("Selected customer id: " + id);
        });

        // display customer name in listview:
        orgTbl2.setCellFactory(lv -> new ListCell<>() {
            @Override
            protected void updateItem(OrgModel item, boolean empty) {
                super.updateItem(item, empty);
                if (empty || item == null) {
                    setText("");
                } else {
                    setText(item.getCustomerName());
                }
            }
        });
    }

    public void loadData() throws SQLException, ClassNotFoundException {
    
        ObservableList<OrgModel> organizationObservableList = FXCollections.observableArrayList();
    
        try{
            PreparedStatement ps = connect().prepareStatement("SELECT CustomerName,CustomerID, Inactive FROM dbo.tbCustomers");
            ResultSet rs=ps.executeQuery();
            System.out.println(rs);

            while (rs.next()) {
                OrgModel org = new OrgModel(rs.getString(1), rs.getString(2), rs.getBoolean(3));
                organizationObservableList.add(organizationObservableList);
            }
            orgTbl2.setItems(data);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Error on Building Data");
        }
    }

    private static Connection connect() throws SQLException {
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
        }catch(ClassNotFoundException cnfe){
            System.err.println("Error: "+cnfe.getMessage());
        }catch(InstantiationException ie){
            System.err.println("Error: "+ie.getMessage());
        }catch(IllegalAccessException iae){
            System.err.println("Error: "+iae.getMessage());
        }
    
        conn = DriverManager.getConnection(url);
        return conn;
    }
    
    public static Connection getConnection() throws SQLException, ClassNotFoundException{
        if(conn !=null && !conn.isClosed())
            return conn;
        conn = connect();
        return conn;
    }    

}

如果你真的想具体地响应鼠标点击,而不是选择变化,可以这样做。 注意到这意味着,例如,如果用户更改选择使用键盘那么将没有响应这种变化。 这可能是有用的,虽然如果你想的只有回应双击一个细胞,等等。

public void initialize (URL url, ResourceBundle resourceBundle) throws SQLException, ClassNotFoundException {
    loadData();

    // display customer name in listview:
    orgTbl2.setCellFactory(lv -> new ListCell<>() {

        {
            setOnMouseClicked(event -> {
                OrgModel item = getItem();
                if (item != null) {
                    String id = item.getId();
                    String customerName = item.getCustomerName();
                    boolean inactive = item.isInactive();
                    // etc ...
                }
            });
        }

        @Override
        protected void updateItem(OrgModel item, boolean empty) {
            super.updateItem(item, empty);
            if (empty || item == null) {
                setText("");
            } else {
                setText(item.getCustomerName());
            }
        }
    });
}
2021-11-22 20:49:18

其他语言

此页面有其他语言版本

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................