Frage

I have a JList<Contract>. Little excerpt from code:

public class Contract
{
    private int houseId;
    public int getHouseId() { return houseId; }
    public void setHouseId(int hId) { houseID = hId; }
    public String toString()
    {
        // want to return house address here somehow.
    }
}
public class House
{
    private int houseId;
    private String address;
    public int getHouseId() { return houseId; }
    public String getAddress() { return address; }
}
public class Registry
{
    private ArrayList<Contract> contracts;
    private ArrayList<House> houses;
    // ...get-methods...
}

In my JList i want to display the address from House class. But i still need the element type to be a Contract or a reference to the Contract. How can this be done?

War es hilfreich?

Lösung

You need to implement custom cell renderers, which would be a good idea anyway (in any real-world application). The renderer (a swing component) will get the Contract object and can grab the house data from there.
Here is tutorial from Oracle.
Advanced: you can mix classes in the model and switch by class from here.
(that one is for JTables, but it's essentially the same).

Andere Tipps

Regardless of the Swing approach you take for the visualization (i.e. custom renderers as already suggested), consider using composition for your classes.

Instead of setHouseId(int hId) in the Contract class, why not just have setHouse(House h)? You could then have a getAddress() on Contract that would just delegate to this.house.getAddress().

There would then be no need for the Registry.

You would then have all the information you need to show in each element of your JList, which would be helpful for the custom renderer.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top