0

I have a DefaultListModel, and I can add and remove items in runtime, but I want to sort them after updates, using a sql.Time Object as comparator, but I don't really get how to do that. he's my code: this DLM its populated in JFrame1

public static final DefaultListModel m = new DefaultListModel();
// for cicle to retrieve from DB and add to DLM
m.addElement(new myObject(String,Time);
mylist.setModel(m)

and its accessed and manipulated from another JFrame using:

JFrame1.m.set(index, myObject); 

It actually update the JList but want to implement a sort method for this.

import java.text.SimpleDateFormat;
import java.sql.Time;
public class Cita implements Comparable<Cita> {
public Time horaInicio;
public Time horaTermino;
public Paciente paciente;
public String actividad;
public String observacion;
public String recordar;
public String ciudad;
public String TipoCita;
public String fecha;
public int idPaciente;
public int idCita;

SimpleDateFormat formatoInicio = new SimpleDateFormat("hh:mm");
SimpleDateFormat formatoTermino = new SimpleDateFormat("hh:mm aa");

public Cita() {
}

public Cita(String fecha, Time horaInicio, Time horaTermino, int idPaciente, String actividad,
        String observacion, String recordar, String ciudad, String tipoCita) {
    this.fecha = fecha;
    this.horaInicio = horaInicio;
    this.horaTermino = horaTermino;
    this.idPaciente = idPaciente;
    this.actividad = actividad;
    this.observacion = observacion;
    this.recordar = recordar;
    this.ciudad = ciudad;
    this.TipoCita = tipoCita;
}

public Cita(int idCita, String fecha, Time horaInicio, Time horaTermino, Paciente paciente, String actividad,
        String observacion, String recordar, String ciudad, String tipoCita) {
    this.idCita = idCita;
    this.fecha = fecha;
    this.horaInicio = horaInicio;
    this.horaTermino = horaTermino;
    this.paciente = paciente;
    this.actividad = actividad;
    this.observacion = observacion;
    this.recordar = recordar;
    this.ciudad = ciudad;
    this.TipoCita = tipoCita;
}

@Override
public int compareTo(Cita o) {
    return (this.getHoraInicio().compareTo(o.getHoraInicio()));
}

public int getIdCita() {
    return idCita;
}

public void setIdCita(int idCita) {
    this.idCita = idCita;
}

public Time getHoraInicio() {
    return horaInicio;
}

public void setHoraInicio(Time horaInicio) {
    this.horaInicio = horaInicio;
}

public Time getHoraTermino() {
    return horaTermino;
}

public void setHoraTermino(Time horaTermino) {
    this.horaTermino = horaTermino;
}

public Paciente getPaciente() {
    return paciente;
}

public void setPaciente(Paciente paciente) {
    this.paciente = paciente;
}

public String getActividad() {
    return actividad;
}

public void setActividad(String actividad) {
    this.actividad = actividad;
}

public String getObservacion() {
    return observacion;
}

public void setObservacion(String observacion) {
    this.observacion = observacion;
}

public String getRecordar() {
    return recordar;
}

public void setRecordar(String recordar) {
    this.recordar = recordar;
}

public String getCiudad() {
    return ciudad;
}

public void setCiudad(String ciudad) {
    this.ciudad = ciudad;
}

public String getTipoCita() {
    return TipoCita;
}

public void setTipoCita(String TipoCita) {
    this.TipoCita = TipoCita;
}

public int getIdPaciente() {
    return idPaciente;
}

public void setIdPaciente(int idPaciente) {
    this.idPaciente = idPaciente;
}

@Override
public int hashCode() {
    int hash = 3;
    hash = 71 * hash + this.idCita;
    return hash;
}

@Override
public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final Cita other = (Cita) obj;
    if (this.idCita != other.idCita) {
        return false;
    }
    return true;
}

public String getFecha() {
    return fecha;
}

public void setFecha(String fecha) {
    this.fecha = fecha;
}

@Override
public String toString() {
    return paciente.getNombre() + ", "
            + formatoInicio.format(horaInicio) + "-"
            + formatoTermino.format(horaTermino);

}

}

a lot of param but i posted the whole class. thanks

1 Answers1

2

You can just have MyObject implements Comparable then compare the Time objects in the compareTo method. Something like

private class MyObject implements Comparable<MyObject> {

    private Time time;
    private String name;

    public MyObject(String name, Time time) {
        this.time = time;
        this.name = name;
    }

    @Override
    public int compareTo(MyObject o) {
        return (this.getTime().compareTo(o.getTime()));
    }

    public Time getTime() {
        return time;
    }

    @Override
    public String toString() {
        return name + " : " + time;
    }

}

Then you can use Collections.sort to sort the list. You will need to add the data from the DefaultlistModel to a separate list, sort that list, remove the elements from the DefaultListModel, then add the sorted elements back. Something like

private void sortModel(DefaultListModel model) {
    List<MyObject> list = new ArrayList<>();
    for (int i = 0; i < model.size(); i++) {
        list.add((MyObject)model.get(i));
    }
    Collections.sort(list);
    model.removeAllElements();
    for (MyObject s : list) {
        model.addElement(s);
    }
}

Below you can see the complete example.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class TestListSort {

    public TestListSort() {
        JList list = createList();
        JButton button = createButton(list);
        JScrollPane scroll = new JScrollPane(list);
        scroll.setPreferredSize(new Dimension(200, 150));

        JFrame frame = new JFrame();
        frame.add(scroll);
        frame.add(button, BorderLayout.SOUTH);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public JButton createButton(final JList list) {
        JButton button = new JButton("Sort");
        button.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                DefaultListModel model = (DefaultListModel)list.getModel();
                sortModel(model);
            }
        });
        return button;
    }

    private void sortModel(DefaultListModel model) {
        List<MyObject> list = new ArrayList<>();
        for (int i = 0; i < model.size(); i++) {
            list.add((MyObject)model.get(i));
        }
        Collections.sort(list);
        model.removeAllElements();
        for (MyObject s : list) {
            model.addElement(s);
        }
    }

    private JList createList() {
        JList list = new JList(createModel());
        return list;
    }

    private DefaultListModel createModel() {
        Random random = new Random();
        DefaultListModel model = new DefaultListModel();
        for (int i = 0; i < 20; i++) {
            long time = random.nextLong();
            Time timeObj = new Time(time);
            model.addElement(new MyObject("Object " + i, timeObj));
        }
        return model;

    }


    private class MyObject implements Comparable<MyObject> {

        private Time time;
        private String name;

        public MyObject(String name, Time time) {
            this.time = time;
            this.name = name;
        }

        @Override
        public int compareTo(MyObject o) {
            return (this.getTime().compareTo(o.getTime()));
        }

        public Time getTime() {
            return time;
        }

        @Override
        public String toString() {
            return name + " : " + time;
        }

    }


    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable(){
            public void run() {
                new TestListSort();
            }
        });
    }
}

UPDATE

Sorry but I don't get the exception. Below is the only thing I changed

private DefaultListModel createModel() {
    Random random = new Random();
    DefaultListModel model = new DefaultListModel();
    for (int i = 0; i < 20; i++) {
        long horaInicio = random.nextLong();
        long horaTermino = random.nextLong();
        Time timeInicio = new Time(horaInicio);
        Time timeTermino = new Time(horaTermino);
        Paciente paciente = new Paciente("Paciente " + i);
        Cita cita = new Cita(i, "blah", timeInicio, timeTermino, paciente,
                "blah", "blah", "blah", "blah", "blah");
        model.addElement(cita);
    }
    return model;

}
......
private void sortModel(DefaultListModel model) {
    List<Cita> list = new ArrayList<>();
    for (int i = 0; i < model.size(); i++) {
        list.add((Cita) model.get(i));
    }
    Collections.sort(list);
    model.removeAllElements();
    for (Cita s : list) {
        model.addElement(s);
    }
}

And I added my own Paciente class to get rid of the uncompilable code

class Paciente {
    private String nombre;

    public Paciente(String nombre) {
        this.nombre = nombre;
    }

    public String getNombre() {
        return nombre;
    }
}
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
  • thanks for your time, Im implementing this but, I am getting an exception, calling Collections.sort(list), expeDiente.Cita cannot be cast to java.lang.Comparable. I dont know why, Cita implements correctly Comparable and overrides the compareTo method. – Jose Miguel Ledón Apr 08 '14 at 05:37
  • Can you post the code for `Cita`. I'll test it out. – Paul Samsotha Apr 08 '14 at 05:43
  • I'm going through it now. – Paul Samsotha Apr 08 '14 at 05:52
  • You can look at my **UPDATE** I don't get any exception. – Paul Samsotha Apr 08 '14 at 06:00
  • Im using two JFrames, where should I put the method? in JFrame A: I the data from from DB, in JFrame B: I make updates, where should I put the method?, and It is a problem if I make it public and static? – Jose Miguel Ledón Apr 08 '14 at 06:06
  • Don't use public static. Pass one as reference to the other through constructor – Paul Samsotha Apr 08 '14 at 06:38
  • but JFrame A call JFrame B using a popoup, so I only update A from B, thats why im using it like that, I tried with the method in both JFrames but still the same exception. when I try using your example with my Cita objects, It work, its like weird – Jose Miguel Ledón Apr 08 '14 at 06:47
  • See if [this answer](http://stackoverflow.com/a/22206175/2587435) for help with accessing objects from different classes. – Paul Samsotha Apr 08 '14 at 06:55
  • I'll do some tests, hope can finder the answers, thanks a lot – Jose Miguel Ledón Apr 08 '14 at 07:13
  • Cant put it to work :/ I dont know why in the basic example it works, with the same jar, but using it in my main project doesnt work, I got this stack trace: java.lang.ClassCastException: expeDiente.Cita cannot be cast to java.lang.Comparable at java.util.ComparableTimSort.countRunAndMakeAscending(ComparableTimSort.java:316) at java.util.ComparableTimSort.sort(ComparableTimSort.java:184) at java.util.Arrays.sort(Arrays.java:1244) at java.util.Collections.sort(Collections.java:166) should I make a new question for this? – Jose Miguel Ledón Apr 08 '14 at 08:45
  • What does `expeDiente.Cita` return? – Paul Samsotha Apr 08 '14 at 09:06
  • Nothing its just to create a "appointment", its the class I posted and u tested remember? – Jose Miguel Ledón Apr 08 '14 at 09:09
  • Sorry, but there's just not enough information for me to help you out. – Paul Samsotha Apr 08 '14 at 09:11