0

I have put together a simple JavaFx with FXML to display a sorted address book (sorting by the first name column). I have defined a simple sorting rule for the first name column, however, the table loads unsorted. I know how to sort a column in the FXML, however, my objective is to see if I can also accomplish the sorting through the controller.

Thanks in advance.

FXML file:

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

<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TableColumn?>
<?import javafx.scene.control.TableView?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>

<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="org.openjfx.mavenfxaddressbooktable.AddressbookController">
    <children>
        <TableView fx:id="tableid" layoutX="133.0" layoutY="62.0" prefHeight="200.0" prefWidth="353.0">
            <columns>
                <TableColumn fx:id="firstnameid" prefWidth="75.0" text="First Name" />
                <TableColumn fx:id="lastnameid" prefWidth="75.0" text="Last Name" />
                <TableColumn fx:id="emailid" prefWidth="201.3333028157552" text="Email Address" />
            </columns>
            <!-- following is the easiest way to sort a column in the table or it can be done in the controller
            <sortOrder>
                <fx:reference source="firstnameid"/>
            </sortOrder> -->
        </TableView>
        <Label layoutX="192.0" layoutY="6.0" text="Sorted Address Book" textFill="#da1b1b">
            <font>
                <Font name="System Bold" size="24.0" />
            </font>
        </Label>
        <TextField fx:id="addfirstname" layoutX="42.0" layoutY="297.0" promptText="First name" />
        <TextField fx:id="addlastname" layoutX="206.0" layoutY="299.0" promptText="Last name" />
        <TextField fx:id="addemail" layoutX="370.0" layoutY="299.0" promptText="Email address" />
        <Button fx:id="addbuttonid" layoutX="277.0" layoutY="361.0" mnemonicParsing="false" `onAction="#addContact" prefHeight="30.0" prefWidth="53.0" text="Add" textFill="#08ab2c">`
            <font>
                <Font name="Tahoma Bold" size="14.0" />
            </font>
        </Button>
    </children>
</AnchorPane>

The Application code

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

import java.io.IOException;

/**
 * JavaFX AddressBookApp
 */
public class AddressBookApp extends Application {

    private static Scene scene;

    @Override
    public void start(Stage stage) throws IOException {
        scene = new Scene(loadFXML("addressbook"));
        stage.setScene(scene);
        stage.setTitle("Address Book");
        stage.show();
    }

    static void setRoot(String fxml) throws IOException {
        scene.setRoot(loadFXML(fxml));
    }

    private static Parent loadFXML(String fxml) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(AddressBookApp.class.getResource(fxml + ".fxml"));
        return fxmlLoader.load();
    }

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

}

The data bean:

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

    public class Person implements Comparable{
    
        private final SimpleStringProperty name = new SimpleStringProperty("");
        private final SimpleStringProperty last = new SimpleStringProperty("");
        private final SimpleStringProperty email = new SimpleStringProperty("");
    
        public Person(String first, String last, String email) {
            setName(first);
            setLast(last);
            setEmail(email);
        }
    
        public final void setEmail(String email) {
            this.email.set(email);
        }
    
        public final void setName(String name) {
            this.name.set(name);
        }
    
        public final void setLast(String last) {
            this.last.set(last);
        }
    
        public String getName() {
            return name.get();
        }
    
        public String getLast() {
            return last.get();
        }
    
        public String getEmail() {
            return email.get();
        }
    
        public static ObservableList<Person> getList() {
            ObservableList<Person> list = FXCollections.observableArrayList();
            list.add(new Person("Zuke", "Adams", "zadam@yahoo.com"));
            list.add(new Person("Bettie", "Burns", "bburns@gmail.com"));
            list.add(new Person("Sal", "Ottaviano", "sottaviano@ibm.com"));
            list.add(new Person("Cindy", "Moraz", "cmoraz@aol.com"));
            list.add(new Person("Alison", "Goldman", "agoldman@sachs.com"));
            
            return list;
        }

The controller code

import java.net.URL;
import java.util.Comparator;
import java.util.ResourceBundle;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
public class AddressbookController implements Initializable {

    @FXML
    private TableView<Person> tableid;
    @FXML
    private TableColumn<TableView, String> firstnameid;
    @FXML
    private TableColumn<?, ?> lastnameid; 
    @FXML
    private TableColumn<?, ?> emailid;
    @FXML
    private TextField addfirstname;
    @FXML
    private TextField addlastname;
    @FXML
    private TextField addemail;
    @FXML
    private Button addbuttonid;
    
    Comparator<String> columnComparator = (String v1 , String v2)->{
        return v1.toLowerCase().compareTo(v2.toLowerCase());
    };

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        firstnameid.setCellValueFactory(new PropertyValueFactory<>("name"));
        lastnameid.setCellValueFactory(new PropertyValueFactory<>("last"));
        emailid.setCellValueFactory(new PropertyValueFactory<>("email"));
        firstnameid.setComparator(columnComparator);
        firstnameid.setSortable(true);
        ObservableList<Person> list = Person.getList();   
        tableid.getItems().addAll(list);
        tableid.sort();
    }    

    @FXML
    private void addContact(ActionEvent event) {
        addbuttonid.setOnAction(new EventHandler<ActionEvent>(){
            @Override
            public void handle(ActionEvent t) {
                Person p = new Person(addfirstname.getText()
                        ,addlastname.getText()
                        ,addemail.getText());
                tableid.getItems().add(p);
             //   ObservableList observe= tableid.getItems();
               // observe.add(p);
                
                tableid.sort();
                addfirstname.clear();
                addlastname.clear();
                addemail.clear();
                
            }//handle()
            
        }//EventHandler()
        
        
        );//addbuttonid.setOnAction()
    }
}

    @Override
    public int compareTo(Object o) {
        return this.getName().compareTo(((Person) o).getName());
    }
}
Anthony
  • 135
  • 1
  • 14
  • 1
    can't try right now - don't you have to add the column to the table's sortOrder? .. yes, see the duplicate: [Sort TableView by certain column Javafx](https://stackoverflow.com/questions/36240142/sort-tableview-by-certain-column-javafx) - you might have typed the words "tableView sort" into the tag search field yourself, or not? just saying :) – kleopatra Aug 20 '20 at 10:14
  • Thank you Kleopatra, that was the problem. It is working now. God bless Julius Caesar and Mark Anthony :-) – Anthony Aug 20 '20 at 11:38
  • they have nothing to do with my victories here – kleopatra Aug 20 '20 at 11:44
  • still don't see you adding the column to the sortOrder .. what's the problem? – kleopatra Sep 27 '20 at 09:36
  • There is no issue here, following your recommendation; I have fixed the problem on Aug-20th. Although, yesterday, I noticed that Stackoverflow has revoked my account and banned me from using the site. The site’s cognoscente has determined my posts were replete with incoherence and ambiguity. Furthermore, they recommended that I revise my existing posts with coherence and clarity. Hence, as a penitent, I revised all posts pedantically to forge a sense of perspicuous clarity to each post, hoping they lift the ban soon. – Anthony Sep 27 '20 at 11:57
  • hmm .. but then, what _is_ the issue? No need to revise a question that was clear and solved :) – kleopatra Sep 27 '20 at 12:00
  • Perhaps, the issue will remain surreptitious to us and only a coterie of site experts are privy to the knowledge :-) – Anthony Sep 27 '20 at 12:33

0 Answers0