Frage

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

War es hilfreich?

Lösung

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;
    }
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top