如何获得JavaFX TableView中的第一列值,就像JTable一样? [英] How to Get First Column Value on click in JavaFX TableView like JTable in swing?

查看:141
本文介绍了如何获得JavaFX TableView中的第一列值,就像JTable一样?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望获得第一列值,因为我们可以使用swing在Jtable中实现。下面是我的jtable代码和图片。

I want to get First column value as we can achieve in Jtable using swing. below is my code and image for jtable.

String Table_Clicked = jTable1.getModel().getValueAt(row, 0).toString();

当我点击名称列值时,您可以在图片中看到它给我第一列值如 8 。但是我选择名称列

As you can see in image when i click to the Name column value eight it gives me first column value like 8. But I select Name Column

那么如何使用TableView Componenet在JavaFX中实现这一点。

So how to achieve this in JavaFX with TableView Componenet.

我从TableView中获取所选的值,如下图所示,包含代码。

I get the selected Value from the TableView as you can see in image below with the code.

   tableview.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
        @Override
        public void changed(ObservableValue observableValue, Object oldValue, Object newValue) {
         if(tableview.getSelectionModel().getSelectedItem() != null) 
            {  
                TableViewSelectionModel selectionModel = tableview.getSelectionModel();
                ObservableList selectedCells = selectionModel.getSelectedCells();
                TablePosition tablePosition = (TablePosition) selectedCells.get(0);
                Object val = tablePosition.getTableColumn().getCellData(newValue);
                System.out.println("Selected value IS :" + val);
            }

         }
     });

所以我想在tableview中获得相同的第一列数据,因为我们可以在Jtable中获得?所以如何获得 NO 值...使用我的上面的代码我得到选定的Cell 的值<8> 打印在控制台..但我想获得第一列价值..帮助我彻底前进。

So I want the same in tableview First column data as we can get in Jtable? so how to get that NO value.. as using my above code I get the value of selected Cell that is eight print in console.. but I want to get First Column Value.. Help me to go thorough Ahead.

谢谢..

数据填写更新TABLEVIEW代码

   PreparedStatement psd = (PreparedStatement) conn.prepareStatement("SELECT No,name FROM FieldMaster");
    psd.execute();
    ResultSet rs = psd.getResultSet();

    for(int i=0 ; i<rs.getMetaData().getColumnCount(); i++){
            //We are using non property style for making dynamic table
            final int j = i;                
            namecol = new TableColumn(rs.getMetaData().getColumnName(i+1));
            namecol.setCellValueFactory(new Callback<CellDataFeatures<ObservableList, String>, ObservableValue<String>>()
            {
            @Override
            public ObservableValue<String> call(CellDataFeatures<ObservableList, String> param) 
            {
                return new SimpleStringProperty(param.getValue().get(j).toString());
            }
        });

            tableview.getColumns().addAll(namecol); 
            System.out.println("Column ["+i+"] ");


        }

            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);

        }
        tableview.setItems(data);
        conn.close();


推荐答案

解决方案

您可以通过调用与所选行对应的模型对象上的getter来检索相关字段。

You can retrieve the relevant field by calling the getter on the model object corresponding to the selected row.

在代码中低于 newValue.getId()调用是关键。

In the code below the newValue.getId() call is the key.

没有Java 8 lambdas:

Without Java 8 lambdas:

final Label selected = new Label();
table.getSelectionModel().selectedItemProperty().addListener(
    new ChangeListener<IdentifiedName>() {
        @Override
        public void changed(
            ObservableValue<? extends IdentifiedName> observable, 
            IdentifiedName oldValue, 
            IdentifiedName newValue
        ) {
            if (newValue == null) {
                selected.setText("");
                return;
            }

            selected.setText("Selected Number: " + newValue.getId());
        }
    }
);

使用Java 8 lambdas:

With Java 8 lambdas:

final Label selected = new Label();
table.getSelectionModel().selectedItemProperty().addListener(
    (observable, oldValue, newValue) -> {
        if (newValue == null) {
            selected.setText("");
            return;
        }

        selected.setText("Selected Number: " + newValue.getId());
    }
);

示例代码

import javafx.application.Application;
import javafx.collections.*;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.*;
import javafx.stage.Stage;

public class TableViewSample extends Application {

    private TableView<IdentifiedName> table = new TableView<>();
    private final ObservableList<IdentifiedName> data =
        FXCollections.observableArrayList(
            new IdentifiedName(3, "three"),
            new IdentifiedName(4, "four"),
            new IdentifiedName(7, "seven"),
            new IdentifiedName(8, "eight"),
            new IdentifiedName(9, "nineses")
        );

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

    @Override
    public void start(Stage stage) {
        TableColumn<IdentifiedName, Integer> idColumn = new TableColumn<>("No");
        idColumn.setMinWidth(100);
        idColumn.setCellValueFactory(
                new PropertyValueFactory<>("id")
        );

        TableColumn<IdentifiedName, String> nameColumn = new TableColumn<>("Name");
        nameColumn.setMinWidth(100);
        nameColumn.setCellValueFactory(
                new PropertyValueFactory<>("name")
        );

        table.setItems(data);
        table.getColumns().setAll(idColumn, nameColumn);
        table.setPrefHeight(180);

        final Label selected = new Label();
        table.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue == null) {
                selected.setText("");
                return;
            }

            selected.setText("Selected Number: " + newValue.getId());
        });

        final VBox layout = new VBox(10);
        layout.setPadding(new Insets(10));
        layout.getChildren().addAll(table, selected);
        VBox.setVgrow(table, Priority.ALWAYS);

        stage.setScene(new Scene(layout));
        stage.show();
    }

    public static class IdentifiedName {
        private final int    id;
        private final String name;

        private IdentifiedName(int id, String name) {
            this.id   = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }
    }
} 

附加答案问题


检查我的更新问题,以便我不能使用它?

check my updated question so I can't use this?

因此,在您的更新中,您可以看到每行数据的类型是 ObservableList< String> ,而在我的回答中,类型是 IdentifiedName 。要使发布的解决方案适用于您的数据类型,更改是微不足道的。相当于 newValue.getId()将是 newValue.get(0),以返回您的第一项所选行的列表。

So in your update you can see that the type of each row's data is ObservableList<String>, whereas in my answer the type is IdentifiedName. To get the posted solution to work for your data type, the change is trivial. The equivalent of newValue.getId() would be newValue.get(0), to return the first item in your list for the selected row.

final Label selected = new Label();
table.getSelectionModel().selectedItemProperty().addListener(
    (observable, oldValue, newValue) -> {
        if (newValue == null) {
            selected.setText("");
            return;
        }

        selected.setText("Selected Number: " + newValue.get(0));
    }
);




还是可以使用identifyname类?那怎么样?

or is it possible to use identifiedname class? then how?

是的,但是您必须对数据库提取代码进行大量更改才能将创建的数据加载到 IdentifiedName class而不是 ObservableList< String> ,这样做会失去数据库加载代码的通用性。

Yes you could, but you would have to make extensive changes to your database fetching code to load the data created into an IdentifiedName class rather than an ObservableList<String> and doing so would lose the generic nature of your database loading code.


我将你的代码实现到我的项目中...... java.lang.ClassCastException:

您需要为数据类型正确设置表和列的类型,而不是我为用例提供的示例类型。

You need to setup the type of your Table and columns correctly for your data types, not the sample ones I provided for my use case.

替换这些类型:

TableView<IdentifiedName>
TableColumn<IdentifiedName, Integer>

使用以下类型:

TableView<ObservableList<String>>
TableColumn<ObservableList<String>, String>

次要建议

我建议您阅读 Java Generics Trail 。 JavaFX中的表在使用泛型时非常复杂,但在表代码中使用正确的泛型可以使编写更容易(只要你使用一个好的IDE,它很好地在需要时猜测泛型)。

I advise taking a refresher by reading up on the Java Generics Trail. Tables in JavaFX are pretty complicated in their use of generics, but using correct generics in your table code can make it easier to write (as long as you are using a good IDE which is good at guessing the generics when needed).

您还可以提供最小,完整,经过测试和读取的示例此类未来的问题(并非所有问题)。构建一个可以帮助您更快地解决您的问题。此外,确保您的代码具有一致的缩进使其更容易阅读。

You also might want to provide an minimal, complete, tested and readable example with future questions of this type (not all questions). Construction of one could help you solve your issues quicker. Also, ensuring your code has consistent indentation makes it easier to read.

这篇关于如何获得JavaFX TableView中的第一列值,就像JTable一样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆