Duvida com jTable

1 resposta
C

ola galera, gostaria que vcs me ajudassem, ja quebrei cabeça e nada.
o negocio eh o seguinte:
eu tenho 2 jFrames, 1 que tem uma jTable, 1 botao de adicionar contato e 1 botao de pesquisar.
e outra jFrame que tem a telinha de cadastrar um contato com varios jTextField para nome, telefone, etc. e mais um botao de cadastrar.

então o que eu estou querendo:
que ao apertar o botao cadastrar, o contato seja cadastrado na jTable e quando eu colocar o nome e apertar o botao de busca ele liste no jTable.
soh que eu nao estou conseguindo, eis o codigo entao para que vcs deem uma olhada

botao de cadastrar.

1 Resposta

javer

Umas dicas:

1) Crie um bean para seu cadastro (para cada campo do cadastro uma propriedade no bean com get e set)

2) Use um TableModel no seu JTable extendendo o AbastractTableModel, e nesse modelo você manipula uma Lista dos beans (algo como lista = new ArrayList())

3) Quando você clicar no Cadastrar você cria um bean com os dados da sua "tela" de cadastro e envia ele para a lista que está no TableModel da tabela através de um método qualquer que adicione um item a lista já existente.

Se você conseguir essa primeira parte ai pode partir para o Filtro do nome na JTable.

Segue um pequeno exemplo que fiz usando o NB6 porque já tenho muita prática nele, você pode estudar o código e adaptar para sua situação.

Só um detalhe: não é "elegante" você usar dois JFrames para fazer o que está fazendo, no caso eu estou utilizando JTabbedPane com duas abas, uma para o cadastro e outra para mostrar a listagem no JTable.

Bean cliente:
package teste;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

/**
 *
 * @author Francisco
 */
public class Cliente {

    public Cliente() {
    }
    private int codigo = 0;
    public static final String PROP_CODIGO = "codigo";
    private String nome;
    public static final String PROP_NOME = "nome";
    private String telefone;
    public static final String PROP_TELEFONE = "telefone";

    public String getTelefone() {
        return telefone;
    }

    public void setTelefone(String telefone) {
        String oldTelefone = this.telefone;
        this.telefone = telefone;
        propertyChangeSupport.firePropertyChange(PROP_TELEFONE, oldTelefone, telefone);
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        String oldNome = this.nome;
        this.nome = nome;
        propertyChangeSupport.firePropertyChange(PROP_NOME, oldNome, nome);
    }

    public int getCodigo() {
        return codigo;
    }

    public void setCodigo(int codigo) {
        int oldCodigo = this.codigo;
        this.codigo = codigo;
        propertyChangeSupport.firePropertyChange(PROP_CODIGO, oldCodigo, codigo);
    }
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }

}
O TableModel (tá bem simples):
package teste;

import java.util.ArrayList;
import javax.swing.table.AbstractTableModel;

/**
 *
 * @author Francisco
 */
public class ClienteTableModel extends AbstractTableModel {

    private static final String[] NOME_COLUNA = new String[]{"Código", "Nome", "Telefone"};
    private static final Class[] TIPO_COLUNA = {Integer.class, String.class, String.class};
    ArrayList<Cliente> lista = new ArrayList<Cliente>();

    public ClienteTableModel() {
    }

    @Override
    public void setValueAt(Object objeto, int linha, int coluna) {
        Cliente item = lista.get(linha);

        switch (coluna) {
            case 0:
                item.setCodigo((Integer) objeto);
                break;
            case 1:
                item.setNome((String) objeto);
                break;
            case 2:
                item.setTelefone((String) objeto);
                break;
        }
        // Atualiza o item na lista
        //lista.set(linha, item);
        fireTableDataChanged();
    }

    public int getRowCount() {
        return lista.size();
    }

    public int getColumnCount() {
        return ClienteTableModel.NOME_COLUNA.length;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return TIPO_COLUNA[columnIndex];
    }

    @Override
    public String getColumnName(int column) {
        return NOME_COLUNA[column];
    }

    public Object getValueAt(int linha, int coluna) {
        Cliente item = (Cliente) lista.get(linha);
        switch (coluna) {
            case 0:
                return item.getCodigo();
            case 1:
                return item.getNome();
            case 2:
                return item.getTelefone();
        }
        return "";
    }

    // Método para colocar uma lista inteira no modelo da JTable
    public void setLista(ArrayList<Cliente> lista) {
        this.lista = lista;
        fireTableDataChanged();
    }

    // Método para adicionar um novo "Cadastro" na lista e também na JTable
    public void addItem(Cliente item) {
        lista.add(item);
        fireTableDataChanged();
    }

    // Método para REMOVER um "Cadastro" da lista e também na JTable
    public void removeItem(Cliente item) {
        lista.remove(item);
        fireTableDataChanged();
    }
}
Um JInternalFrame que fiz para montar a tela (cadastro e listagem dentro de um JTabbedPane):
/*
 * ClienteUI.java
 *
 * Created on 17/11/2009, 06:51:57
 */

package teste;

/**
 *
 * @author Francisco
 */
public class ClienteUI extends javax.swing.JInternalFrame {

    ClienteTableModel modeloClientes;

    /** Creates new form ClienteUI */
    public ClienteUI() {
        initComponents();

        // Inicializar o model para tabela (JTable)
        modeloClientes = new ClienteTableModel();
        tabelaClientes.setModel(modeloClientes);
    }

    
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        tab = new javax.swing.JTabbedPane();
        tabCadastro = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        campoNome = new javax.swing.JTextField();
        campoTelefone = new javax.swing.JTextField();
        btnCadastrar = new javax.swing.JButton();
        tabListagem = new javax.swing.JPanel();
        caixaListagem = new javax.swing.JScrollPane();
        tabelaClientes = new javax.swing.JTable();
        jLabel3 = new javax.swing.JLabel();
        campoNomeFiltro = new javax.swing.JTextField();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Cadastro de Clientes");

        tab.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N

        jLabel1.setText("Nome");

        jLabel2.setText("Telefone");

        btnCadastrar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnCadastrar.setText("Cadastrar");
        btnCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCadastrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout tabCadastroLayout = new javax.swing.GroupLayout(tabCadastro);
        tabCadastro.setLayout(tabCadastroLayout);
        tabCadastroLayout.setHorizontalGroup(
            tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabCadastroLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(tabCadastroLayout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(18, 18, 18)
                        .addComponent(campoNome, javax.swing.GroupLayout.DEFAULT_SIZE, 537, Short.MAX_VALUE))
                    .addGroup(tabCadastroLayout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(campoTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnCadastrar, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        tabCadastroLayout.setVerticalGroup(
            tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabCadastroLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(campoNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabCadastroLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(campoTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 162, Short.MAX_VALUE)
                .addComponent(btnCadastrar)
                .addContainerGap())
        );

        tab.addTab("Cadastro", tabCadastro);

        tabelaClientes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        caixaListagem.setViewportView(tabelaClientes);

        jLabel3.setText("Filtro:");

        javax.swing.GroupLayout tabListagemLayout = new javax.swing.GroupLayout(tabListagem);
        tabListagem.setLayout(tabListagemLayout);
        tabListagemLayout.setHorizontalGroup(
            tabListagemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabListagemLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(tabListagemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(caixaListagem, javax.swing.GroupLayout.DEFAULT_SIZE, 582, Short.MAX_VALUE)
                    .addGroup(tabListagemLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(campoNomeFiltro, javax.swing.GroupLayout.DEFAULT_SIZE, 544, Short.MAX_VALUE)))
                .addContainerGap())
        );
        tabListagemLayout.setVerticalGroup(
            tabListagemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(tabListagemLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(caixaListagem, javax.swing.GroupLayout.PREFERRED_SIZE, 211, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(tabListagemLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(campoNomeFiltro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        tab.addTab("Listagem...", tabListagem);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tab, javax.swing.GroupLayout.DEFAULT_SIZE, 607, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(tab, javax.swing.GroupLayout.PREFERRED_SIZE, 283, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(29, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void btnCadastrarActionPerformed(java.awt.event.ActionEvent evt) {
        // adicionar um novo bean Cliente ao modelo da JTable
        Cliente cliente = new Cliente();
        cliente.setNome(campoNome.getText());
        cliente.setTelefone(campoTelefone.getText());
        modeloClientes.addItem(cliente);
        // pronto, depois desse ponto vc ja pode ver seu novo cadastro na listagem da JTable
    }


    // Variables declaration - do not modify
    private javax.swing.JButton btnCadastrar;
    private javax.swing.JScrollPane caixaListagem;
    private javax.swing.JTextField campoNome;
    private javax.swing.JTextField campoNomeFiltro;
    private javax.swing.JTextField campoTelefone;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTabbedPane tab;
    private javax.swing.JPanel tabCadastro;
    private javax.swing.JPanel tabListagem;
    private javax.swing.JTable tabelaClientes;
    // End of variables declaration

}
Como usei o NB e ele usa um outro arquivo para montar a tela visualmente (é apenas um arquivo XML), segue também esse arquivo, caso você queira tentar pelo NB.
<?xml version="1.0" encoding="UTF-8" ?>

<Form version="1.3" maxVersion="1.7" type="org.netbeans.modules.form.forminfo.JInternalFrameFormInfo">
  <Properties>
    <Property name="closable" type="boolean" value="true"/>
    <Property name="iconifiable" type="boolean" value="true"/>
    <Property name="maximizable" type="boolean" value="true"/>
    <Property name="resizable" type="boolean" value="true"/>
    <Property name="title" type="java.lang.String" value="Cadastro de Clientes"/>
  </Properties>
  <SyntheticProperties>
    <SyntheticProperty name="formSizePolicy" type="int" value="1"/>
  </SyntheticProperties>
  <AuxValues>
    <AuxValue name="FormSettings_autoResourcing" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_autoSetComponentName" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_generateFQN" type="java.lang.Boolean" value="true"/>
    <AuxValue name="FormSettings_generateMnemonicsCode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_i18nAutoMode" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_layoutCodeTarget" type="java.lang.Integer" value="1"/>
    <AuxValue name="FormSettings_listenerGenerationStyle" type="java.lang.Integer" value="0"/>
    <AuxValue name="FormSettings_variablesLocal" type="java.lang.Boolean" value="false"/>
    <AuxValue name="FormSettings_variablesModifier" type="java.lang.Integer" value="2"/>
  </AuxValues>

  <Layout>
    <DimensionLayout dim="0">
      <Group type="103" groupAlignment="0" attributes="0">
          <Component id="tab" alignment="0" pref="607" max="32767" attributes="0"/>
      </Group>
    </DimensionLayout>
    <DimensionLayout dim="1">
      <Group type="103" groupAlignment="0" attributes="0">
          <Group type="102" alignment="0" attributes="0">
              <Component id="tab" min="-2" pref="283" max="-2" attributes="0"/>
              <EmptySpace pref="29" max="32767" attributes="0"/>
          </Group>
      </Group>
    </DimensionLayout>
  </Layout>
  <SubComponents>
    <Container class="javax.swing.JTabbedPane" name="tab">
      <Properties>
        <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
          <Font name="Tahoma" size="11" style="1"/>
        </Property>
      </Properties>

      <Layout class="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout"/>
      <SubComponents>
        <Container class="javax.swing.JPanel" name="tabCadastro">
          <Constraints>
            <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout$JTabbedPaneConstraintsDescription">
              <JTabbedPaneConstraints tabName="Cadastro">
                <Property name="tabTitle" type="java.lang.String" value="Cadastro"/>
              </JTabbedPaneConstraints>
            </Constraint>
          </Constraints>

          <Layout>
            <DimensionLayout dim="0">
              <Group type="103" groupAlignment="0" attributes="0">
                  <Group type="102" attributes="0">
                      <EmptySpace max="-2" attributes="0"/>
                      <Group type="103" groupAlignment="0" attributes="0">
                          <Group type="102" alignment="0" attributes="0">
                              <Component id="jLabel1" min="-2" max="-2" attributes="0"/>
                              <EmptySpace min="-2" pref="18" max="-2" attributes="0"/>
                              <Component id="campoNome" pref="537" max="32767" attributes="0"/>
                          </Group>
                          <Group type="102" alignment="0" attributes="0">
                              <Component id="jLabel2" min="-2" max="-2" attributes="0"/>
                              <EmptySpace max="-2" attributes="0"/>
                              <Component id="campoTelefone" min="-2" pref="107" max="-2" attributes="0"/>
                          </Group>
                          <Component id="btnCadastrar" alignment="1" min="-2" max="-2" attributes="0"/>
                      </Group>
                      <EmptySpace max="-2" attributes="0"/>
                  </Group>
              </Group>
            </DimensionLayout>
            <DimensionLayout dim="1">
              <Group type="103" groupAlignment="0" attributes="0">
                  <Group type="102" alignment="0" attributes="0">
                      <EmptySpace max="-2" attributes="0"/>
                      <Group type="103" groupAlignment="3" attributes="0">
                          <Component id="jLabel1" alignment="3" min="-2" max="-2" attributes="0"/>
                          <Component id="campoNome" alignment="3" min="-2" max="-2" attributes="0"/>
                      </Group>
                      <EmptySpace type="unrelated" max="-2" attributes="0"/>
                      <Group type="103" groupAlignment="3" attributes="0">
                          <Component id="jLabel2" alignment="3" min="-2" max="-2" attributes="0"/>
                          <Component id="campoTelefone" alignment="3" min="-2" max="-2" attributes="0"/>
                      </Group>
                      <EmptySpace pref="162" max="32767" attributes="0"/>
                      <Component id="btnCadastrar" min="-2" max="-2" attributes="0"/>
                      <EmptySpace max="-2" attributes="0"/>
                  </Group>
              </Group>
            </DimensionLayout>
          </Layout>
          <SubComponents>
            <Component class="javax.swing.JLabel" name="jLabel1">
              <Properties>
                <Property name="text" type="java.lang.String" value="Nome"/>
              </Properties>
            </Component>
            <Component class="javax.swing.JLabel" name="jLabel2">
              <Properties>
                <Property name="text" type="java.lang.String" value="Telefone"/>
              </Properties>
            </Component>
            <Component class="javax.swing.JTextField" name="campoNome">
            </Component>
            <Component class="javax.swing.JTextField" name="campoTelefone">
            </Component>
            <Component class="javax.swing.JButton" name="btnCadastrar">
              <Properties>
                <Property name="font" type="java.awt.Font" editor="org.netbeans.beaninfo.editors.FontEditor">
                  <Font name="Tahoma" size="11" style="1"/>
                </Property>
                <Property name="text" type="java.lang.String" value="Cadastrar"/>
              </Properties>
              <Events>
                <EventHandler event="actionPerformed" listener="java.awt.event.ActionListener" parameters="java.awt.event.ActionEvent" handler="btnCadastrarActionPerformed"/>
              </Events>
            </Component>
          </SubComponents>
        </Container>
        <Container class="javax.swing.JPanel" name="tabListagem">
          <Constraints>
            <Constraint layoutClass="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout" value="org.netbeans.modules.form.compat2.layouts.support.JTabbedPaneSupportLayout$JTabbedPaneConstraintsDescription">
              <JTabbedPaneConstraints tabName="Listagem...">
                <Property name="tabTitle" type="java.lang.String" value="Listagem..."/>
              </JTabbedPaneConstraints>
            </Constraint>
          </Constraints>

          <Layout>
            <DimensionLayout dim="0">
              <Group type="103" groupAlignment="0" attributes="0">
                  <Group type="102" attributes="0">
                      <EmptySpace max="-2" attributes="0"/>
                      <Group type="103" groupAlignment="0" attributes="0">
                          <Component id="caixaListagem" alignment="0" pref="582" max="32767" attributes="0"/>
                          <Group type="102" alignment="0" attributes="0">
                              <Component id="jLabel3" min="-2" max="-2" attributes="0"/>
                              <EmptySpace type="unrelated" max="-2" attributes="0"/>
                              <Component id="campoNomeFiltro" pref="544" max="32767" attributes="0"/>
                          </Group>
                      </Group>
                      <EmptySpace max="-2" attributes="0"/>
                  </Group>
              </Group>
            </DimensionLayout>
            <DimensionLayout dim="1">
              <Group type="103" groupAlignment="0" attributes="0">
                  <Group type="102" alignment="0" attributes="0">
                      <EmptySpace max="-2" attributes="0"/>
                      <Component id="caixaListagem" min="-2" pref="211" max="-2" attributes="0"/>
                      <EmptySpace type="unrelated" max="-2" attributes="0"/>
                      <Group type="103" groupAlignment="3" attributes="0">
                          <Component id="jLabel3" alignment="3" min="-2" max="-2" attributes="0"/>
                          <Component id="campoNomeFiltro" alignment="3" min="-2" max="-2" attributes="0"/>
                      </Group>
                      <EmptySpace max="32767" attributes="0"/>
                  </Group>
              </Group>
            </DimensionLayout>
          </Layout>
          <SubComponents>
            <Container class="javax.swing.JScrollPane" name="caixaListagem">
              <AuxValues>
                <AuxValue name="autoScrollPane" type="java.lang.Boolean" value="true"/>
              </AuxValues>

              <Layout class="org.netbeans.modules.form.compat2.layouts.support.JScrollPaneSupportLayout"/>
              <SubComponents>
                <Component class="javax.swing.JTable" name="tabelaClientes">
                  <Properties>
                    <Property name="model" type="javax.swing.table.TableModel" editor="org.netbeans.modules.form.editors2.TableModelEditor">
                      <Table columnCount="4" rowCount="4">
                        <Column editable="true" title="Title 1" type="java.lang.Object"/>
                        <Column editable="true" title="Title 2" type="java.lang.Object"/>
                        <Column editable="true" title="Title 3" type="java.lang.Object"/>
                        <Column editable="true" title="Title 4" type="java.lang.Object"/>
                      </Table>
                    </Property>
                  </Properties>
                </Component>
              </SubComponents>
            </Container>
            <Component class="javax.swing.JLabel" name="jLabel3">
              <Properties>
                <Property name="text" type="java.lang.String" value="Filtro:"/>
              </Properties>
            </Component>
            <Component class="javax.swing.JTextField" name="campoNomeFiltro">
            </Component>
          </SubComponents>
        </Container>
      </SubComponents>
    </Container>
  </SubComponents>
</Form>

Espero que te ajude, na verdade essa parte de trabalhar com JTable é meio chatinha mesmo, mas eu aconselho muito que você já aprenda do jeito mais "certo" possível.

Criado 16 de novembro de 2009
Ultima resposta 17 de nov. de 2009
Respostas 1
Participantes 2