как правильно отображать строковые значения из simpleStringProperty в listView - PullRequest
0 голосов
/ 27 мая 2019

Я хочу отобразить значения из ObservableList типа ManagerData в виде списка.

Класс ManagerData состоит из 2 учетных записей и пароля SimpleStringProperty.

Но, когда я заполняю представление списка с помощьюданные отображают значения SimpleStringProperty как «model.ManagerData@1a697fac», «model.ManagerData@3c42f0f0» и «model.ManagerData@fc87ab8» в виде списка, а не значение SimpleStringProperty.

Класс Controller:

package manager;

import com.jfoenix.controls.JFXListView;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import misci.AlertBuilder;
import misci.DB;
import model.ManagerData;

import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

public class Controller implements Initializable {

@FXML private JFXListView listView;
@FXML private TextField txtAccount, txtPassword;

private final ObservableList listData = FXCollections.observableArrayList();
private String sql;
private ResultSet rs;


@FXML private void loadAction() {
    sql = "select * from account";
    rs = DB.executeQuery(sql);

    if (rs != null) {
        try {
            while (rs.next()) {
                listData.addAll(new ManagerData(rs.getString("name")));
                listView.setItems(listData);
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}

@Override public void initialize(URL location, ResourceBundle resources) { }
}

Класс-оболочка ManagerData:

package model;

import javafx.beans.property.SimpleStringProperty;

public class ManagerData {

private final SimpleStringProperty accountName, password;

public ManagerData(){
    this.accountName = new SimpleStringProperty();
    this.password = new SimpleStringProperty();
}

public ManagerData(String name){
    this.accountName = new SimpleStringProperty(name);
    this.password = new SimpleStringProperty();
}

public ManagerData(String name, String password){
    this.accountName = new SimpleStringProperty(name);
    this.password = new SimpleStringProperty(password);
}


//setter methods
public void setAccountName(String accountName){
    this.accountName.set(accountName);
}

public void setPassword(String password){
    this.password.set(password);
}


//getter methods
public String getAccountName() {
    return this.accountName.get();
}

public String getPassword() {
    return this.password.get();
}
}

GUI

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

<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXListView?>
<?import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIconView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.effect.DropShadow?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.StackPane?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="550.0" prefWidth="850.0" style="-fx-background-color: white;" xmlns="http://javafx.com/javafx/8.0.141" xmlns:fx="http://javafx.com/fxml/1" fx:controller="manager.Controller">
   <children>
      <StackPane prefHeight="150.0" prefWidth="200.0" style="-fx-background-color: white;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="30.0">
         <children>
            <AnchorPane prefHeight="200.0" prefWidth="200.0">
               <children>
                  <JFXListView fx:id="listView" depth="1" editable="true" focusTraversable="false" layoutX="530.0" layoutY="41.0" showTooltip="true" stylesheets="@listViewStyles.css" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="500.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="15.0" />
               </children></AnchorPane>
         </children></StackPane>
      <AnchorPane layoutX="39.0" layoutY="41.0" prefHeight="45.0" style="-fx-background-color: white;" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
         <effect>
            <DropShadow blurType="GAUSSIAN" color="#616161" height="5.63" offsetY="2.5" radius="0.9075" width="0.0" />
         </effect>
         <children>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="47.0" layoutY="19.0" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="MENU" size="20" />
               </graphic>
            </JFXButton>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="715.0" onAction="#addAction" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="90.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="PLUS" size="20" />
               </graphic>
            </JFXButton>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="760.0" onAction="#loadAction" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="45.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="DOWNLOAD" size="20" />
               </graphic>
            </JFXButton>
            <JFXButton contentDisplay="GRAPHIC_ONLY" focusTraversable="false" layoutX="661.0" layoutY="38.0" prefWidth="45.0" ripplerFill="#8d8d8dd6" style="-fx-background-radius: 0em; -fx-border-radius: 0em;" AnchorPane.bottomAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
               <graphic>
                  <MaterialDesignIconView fill="#616161" glyphName="DOTS_VERTICAL" size="20" />
               </graphic>
            </JFXButton>
            <HBox alignment="CENTER" layoutX="92.0" layoutY="10.0" spacing="20.0" AnchorPane.bottomAnchor="10.0" AnchorPane.leftAnchor="92.0" AnchorPane.rightAnchor="138.0" AnchorPane.topAnchor="10.0">
               <children>
                  <TextField fx:id="txtAccount" alignment="CENTER" focusTraversable="false" prefWidth="300.0" promptText="Account Name" style="-fx-background-radius: 1em; -fx-border-radius: 1em; -fx-background-insets: 0; -fx-background-color: #F5F5F5; -fx-text-fill: #616161;" />
                  <TextField fx:id="txtPassword" alignment="CENTER" focusTraversable="false" prefWidth="300.0" promptText="Password" style="-fx-background-radius: 1em; -fx-border-radius: 1em; -fx-background-insets: 0; -fx-background-color: #F5F5F5; -fx-text-fill: #616161;" />
               </children>
            </HBox>
         </children>
      </AnchorPane>
   </children>
</AnchorPane>

1 Ответ

0 голосов
/ 27 мая 2019

По умолчанию в представлении списка будет отображаться строковое представление вашего объекта, которое определяется toString(), поэтому вы должны переопределить toString() в ManagerData классе и заставить его возвращать любую информацию, которая, по вашему мнению, имеет отношение к отображению,Если вы не определите CellFactory для настройки того, что должно отображаться в ячейках, что более уместно, чем настройка toString для отображения

listView.setCellFactory(param -> new ListCell< ManagerData >() {
@Override
protected void updateItem(ManagerData item, boolean empty) {
    super.updateItem(item, empty);

    if (empty || item.getAccountName() == null) {
        setText("");
    } else {
        setText(item.getAccountName());
    }
}

});

...