Originariamente inviato da cifa
Ora io ho un oggetto il quale toString è definito come "Blablabla\n Blabla bla\n xxx \n zzz\n" e necessito che sia visualizzato in una jlist con le andate a capo messe correttamente. Come posso fare ? Ci sono soluzioni alternative ?
La soluzione sta nel definire un proprio ListCellRenderer facendo in modo che il suo unico metodo (getListCellRendererComponent) restituisca ad esempio una istanza di JTextArea, in quanto andrà a formattare correttamente la stringa in base agli escape.
Poichè non conosco la struttura dati di cui disponi, nel mio esempio andrò ad utilizzare la classe Persona, nota toString():
codice:
public class Persona {
private String nome;
private String cognome;
private int eta;
public Persona(String nome, String cognome, int eta) {
this.nome = nome;
this.cognome = cognome;
this.eta = eta;
}
@Override
public String toString(){
return this.nome + "\n" + this.cognome + "\n" + this.eta;
}
// ...
}
Di seguito, una implementazione dell'interfaccia javax.swing.ListCellRenderer, che come detto utilizza istanze della classe JTextArea:
codice:
/**
* @(#)MyListCellRender.java
*
*
* @author Vincenzo
* @version 1.00 2011/6/1
*/
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
public class MyListCellRenderer extends JTextArea implements ListCellRenderer {
/**
* Creates a new instance of <code>MyListCellRenderer</code>.
*/
public MyListCellRenderer() {
this.setOpaque(true);
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus){
this.setText( value.toString() );
if( isSelected ){
this.setBackground( list.getSelectionBackground() );
this.setForeground( list.getSelectionForeground() );
} else {
this.setBackground( ( index % 2 != 0 ) ? new Color(191, 239, 255) : list.getBackground() );
this.setForeground( list.getForeground() );
}
Border insideBorder = BorderFactory.createEmptyBorder(3, 1, 3, 1);
Border outsideBorder = cellHasFocus ? UIManager.getBorder("List.focusCellHighlightBorder") : BorderFactory.createEmptyBorder(1, 1, 1, 1);
setBorder(BorderFactory.createCompoundBorder(outsideBorder, insideBorder));
setComponentOrientation(list.getComponentOrientation());
setEnabled(list.isEnabled()); // se la lista è modificabile, deve esserlo anche il componente
setFont(list.getFont());
return this;
}
}
Per dare maggiore idea che si tratta di una lista ho fatto in modo che le celle presentano in modo alterno lo sfondo bianco (default) e azzurro. Questo è anche un modo possibile di impiegare il parametro index del metodo.
Se vuoi testare il tutto, compila ed esegui:
codice:
/**
* @(#)Main.java
*
*
* @author Vincenzo
* @version 1.00 2011/6/1
*/
import javax.swing.*;
import java.util.Random;
public class Main extends JFrame{
/**
* Creates a new instance of <code>Main</code>.
*/
public Main() {
super("Esempio ListCellRenderer");
JList list = new JList();
list.setCellRenderer( new MyListCellRenderer() );
list.setListData( this.getListData() );
this.add( list );
this.setDefaultCloseOperation( this.EXIT_ON_CLOSE );
this.pack();
this.setVisible(true);
}
private Persona[] getListData(){
String names[] = {"Andrea", "Enzo", "Simone", "Guido"};
String surnames[] = {"Bianchi", "Rossi", "Verdi", "Neri"};
Persona data[] = new Persona[10];
Random r = new Random();
for(int i = 0; i < data.length; i++)
data[i] = new Persona( names[r.nextInt(names.length)], surnames[r.nextInt(surnames.length)], r.nextInt(109)+1 );
return data;
}
/**
* @param args the command line arguments
*/
public static void main(String[] args){
new Main();
}
}