Atualizar Jlist ao adicionar, remover ou editar

5 respostas
T

Pessoal tenho um jlist e quando adiciono algo a ele simplesmente tenho que fechar a janelae abrir de novo para que o dado apareça. o que devo fazer para atualizar automaticamente?

abraços

5 Respostas

F

Você pode criar um Model:

*
 * @author Fabrício Jorge
 */
public class ModelJListFPJ extends AbstractListModel {

    private List lista;

    public ModelJListFPJ(List lista){
        this.lista = lista;
    }

    @Override
    public int getSize() {
        return this.lista.size();
    }

    @Override
    public Object getElementAt(int index) {
        return this.lista.get(index);
    }
}

Você trabalharia com uma List, adicionando e removendo elementos dessa List, e depois recarregando seu componente JList. Ex:

List<String> nomes = new ArrayList<String>();
         //Obtem o elemento a ser removido
         String e = (String)JLista.getModel().getElementAt(JLista.getSelectedIndex());
         //Remove o elemento do java.util.List
         nomes.remove(e);
 
         //Recarregar os elementos do JList
         ModelJListFPJ modelo = new ModelJListFPJ(nomes);
         JLista.setModel(modelo);
V

Como vc está fazendo para adicionar elementos no seu JList?

E

Se puder, use o Glazed Lists, que já toma conta disso para você automaticamente.

http://publicobject.com/glazedlists/

T

Uso um modelo que implementa ListModel!

entao faço assim:

AvantListModelModeloTelefone;

Listtelefones = condominio.getTelefones();
ModeloTelefone = new AvantListModel(listaTelefones, telefones);

esse avant é um framework de um amigo que ta no github!

E

Exemplo do Glazed Lists:

package guj;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.util.Random;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

import ca.odell.glazedlists.BasicEventList;
import ca.odell.glazedlists.EventList;
import ca.odell.glazedlists.swing.EventListModel;
import ca.odell.glazedlists.util.concurrent.Lock;

class Cliente implements Comparable<Cliente> {
	public Cliente (final String nome, final String telefone, final int codigo) {
		this.nome = nome; this.telefone = telefone; this.codigo = codigo;
	}
	@Override public String toString() { return getNome(); }
	public String getNome() { return nome; }
	public String getTelefone() { return telefone; }
	public int getCodigo() { return codigo; }
	@Override public int compareTo (Cliente that) { return Integer.valueOf(this.codigo).compareTo(that.codigo); }
	private String nome;
	private String telefone;
	private int codigo;
}

/**
 * Este exemplo requer o uso da seguinte biblioteca:
 * Glazed Lists - http://publicobject.com/glazedlists/
 */
public class ExemploGlazedLists extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JScrollPane scpList = null;
	private JList lstList = null;
	private JButton btnAdicionar = null;
	private JButton btnRemover = null;
	private JButton btnLimpar = null;
	private JPanel pnlBotoes = null;
	
	private EventList<Cliente> clientes = new BasicEventList<Cliente>();

	private int codigo;
	private Random rand = new Random();
	
	/**
	 * This method initializes scpList	
	 * 	
	 * @return javax.swing.JScrollPane	
	 */
	private JScrollPane getScpList() {
		if (scpList == null) {
			scpList = new JScrollPane();
			scpList.setViewportView(getLstList());
		}
		return scpList;
	}

	/**
	 * This method initializes lstList	
	 * 	
	 * @return javax.swing.JList	
	 */
	private JList getLstList() {
		if (lstList == null) {
			lstList = new JList();
			lstList.setModel(new EventListModel<Cliente> (clientes));
		}
		return lstList;
	}

	
	/**
	 * This method initializes btnAdicionar	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnAdicionar() {
		if (btnAdicionar == null) {
			btnAdicionar = new JButton();
			btnAdicionar.setText("Adicionar");
			btnAdicionar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					Lock lock = clientes.getReadWriteLock().writeLock();
					try {
						lock.lock();
						clientes.add (new Cliente ("Cliente " + codigo, "888-8889", codigo));
						codigo++;
					} finally {
						lock.unlock();
					}
				}
			});
		}
		return btnAdicionar;
	}

	/**
	 * This method initializes btnRemover	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnRemover() {
		if (btnRemover == null) {
			btnRemover = new JButton();
			btnRemover.setText("Remover");
			btnRemover.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					Lock lock = clientes.getReadWriteLock().writeLock();
					try {
						lock.lock();
						// Aqui vamos remover um cliente qualquer.
						if (clientes.size() > 0) 
							clientes.remove(rand.nextInt (clientes.size()));
					} finally {
						lock.unlock();
					}
				}
			});
		}
		return btnRemover;
	}

	/**
	 * This method initializes btnLimpar	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getBtnLimpar() {
		if (btnLimpar == null) {
			btnLimpar = new JButton();
			btnLimpar.setText("Limpar");
			btnLimpar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					Lock lock = clientes.getReadWriteLock().writeLock();
					try {
						lock.lock();
						clientes.clear();
					} finally {
						lock.unlock();
					}
				}
			});
		}
		return btnLimpar;
	}

	/**
	 * This method initializes pnlBotoes	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getPnlBotoes() {
		if (pnlBotoes == null) {
			pnlBotoes = new JPanel();
			pnlBotoes.setLayout(new FlowLayout());
			pnlBotoes.add(getBtnAdicionar());
			pnlBotoes.add(getBtnRemover());
			pnlBotoes.add(getBtnLimpar());
		}
		return pnlBotoes;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				ExemploGlazedLists thisClass = new ExemploGlazedLists();
				thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				thisClass.setVisible(true);
			}
		});
	}

	/**
	 * This is the default constructor
	 */
	public ExemploGlazedLists() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(300, 200);
		this.setContentPane(getJContentPane());
		this.setTitle("Exemplo Glazed Lists - JList");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jContentPane = new JPanel();
			jContentPane.setLayout(new BorderLayout());
			jContentPane.add(getScpList(), BorderLayout.CENTER);
			jContentPane.add(getPnlBotoes(), BorderLayout.SOUTH);
		}
		return jContentPane;
	}

}

Clique em “Adicionar”, “Remover” ou “Limpar” para adicionar um cliente, remover um ao acaso, ou então limpar tudo.

Criado 8 de junho de 2010
Ultima resposta 8 de jun. de 2010
Respostas 5
Participantes 4