Problema ao enviar parametro de um JTable para outra classe

2 respostas
S

Hello World amigos, estou trabalhando com java e tantando ter o retorno de um JTable que esta funcionando corretamente, porem nao tenho a minima ideia de como fazer ele enviar na hora que eu seleciono e linha ele abrir e preencher o meu formulario CadastroCyberCrime.java vejam como esta minha classe JTable que preenche corretamente.

view plaincopy to clipboardprint?
/*

  • ResultsetTable.java
  • Created on 19 de Novembro de 2007, 08:14
  • To change this template, choose Tools | Template Manager
  • and open the template in the editor.
    */

package listagems;

/**
*

  • @author kleber
    */
import java.awt.<em>;

import java.awt.event.</em>;

import java.sql.<em>;

import java.util.</em>;

import javax.swing.<em>;

import javax.swing.table.</em>;

public class ResultsetTable {

public static void main(String[] args) {   
    JFrame frame = new ResultSetFrame();   
    frame.show();   
}

}

/* this class is the base class for the scrolling and the
caching result set table model. It stores the result set
and its metadata.
*/

abstract class ResultSetTableModel extends AbstractTableModel {

public ResultSetTableModel(ResultSet aResultSet) {

rs = aResultSet;

try {

rsmd = rs.getMetaData();

} catch(SQLException e) {

System.out.println("Error " + e);

}

}
public String getColumnName(int c) {   
    try {   
        return rsmd.getColumnName(c + 1);   
    } catch(SQLException e) {   
        System.out.println("Error " + e);   
        return "";   
    }   
}   
   
public int getColumnCount() {   
    try {   
        return rsmd.getColumnCount();   
    } catch(SQLException e) {   
        System.out.println("Error " + e);   
        return 0;   
    }   
}   
   
protected ResultSet getResultSet() {   
    return rs;   
}   
   
private ResultSet rs;   
private ResultSetMetaData rsmd;

}

/* this class uses a scrolling cursor, a JDBC 2 feature
*/

class ScrollingResultSetTableModel extends ResultSetTableModel {

public ScrollingResultSetTableModel(ResultSet aResultSet) {

super(aResultSet);

}
public Object getValueAt(int r, int c) {   
    try {   
        ResultSet rs = getResultSet();   
        rs.absolute(r + 1);   
        return rs.getObject(c + 1);   
    } catch(SQLException e) {   
        System.out.println("Error " + e);   
        return null;   
    }   
}   
   
public int getRowCount() {   
    try {   
        ResultSet rs = getResultSet();   
        rs.last();   
        return rs.getRow();   
    } catch(SQLException e) {   
        System.out.println("Error " + e);   
        return 0;   
    }   
}

}

/* this class caches the result set data; it can be used
if scrolling cursors are not supported
*/

class CachingResultSetTableModel extends ResultSetTableModel {

public CachingResultSetTableModel(ResultSet aResultSet) {

super(aResultSet);

try {

cache = new ArrayList();

int cols = getColumnCount();

ResultSet rs = getResultSet();
/* place all data in an array list of Object[] arrays  
        We don't use an Object[][] because we don't know  
        how many rows are in the result set  
      */   
           
        while (rs.next()) {   
            Object[] row = new Object[cols];   
            for (int j = 0; j &lt; row.length; j++)   
                row[j] = rs.getObject(j + 1);   
            cache.add(row);   
        }   
    } catch(SQLException e) {   
        System.out.println("Error " + e);   
    }   
}   
   
public Object getValueAt(int r, int c) {   
    if (r &lt; cache.size())   
        return ((Object[])cache.get(r))[c];   
    else   
        return null;   
}   
   
public int getRowCount() {   
    return cache.size();   
}   
   
private ArrayList cache;

}

class ResultSetFrame extends JFrame

implements ActionListener {

public ResultSetFrame() {

setTitle(Resultado da Pesquisa);

setBounds(200,200,600,80);
setResizable(false);   
       
    //setExtendedState(this.MAXIMIZED_BOTH);   
    addWindowListener(new WindowAdapter() {   
        public void windowClosing(WindowEvent e) {   
            System.exit(0);   
        }   
    } );   
       
  /* find all tables in the database and add them to  
     a combo box  
   */   
       
    Container contentPane = getContentPane();   
    tableNames = new JComboBox();   

    jlCodigoDe = new JLabel("Buscar código de:", SwingConstants.RIGHT);           
    jlCodigoAte = new JLabel("Ate:", SwingConstants.RIGHT);           
       
    jbBuscar = new JButton();   

    jtfNome = new JTextField();   
    jtfCodigoDe = new JTextField();   
    jtfCodigoAte = new JTextField();   
    jtfCodigoAte.setSize(20,10);   
       
       
       
    jtfCodigoDe.addActionListener(this);   
    jtfCodigoAte.addActionListener(this);   
           
    jtfNome.addActionListener(this);   
    jbBuscar.addActionListener(this);   
       
       
    tableNames.addActionListener(this);   
    JPanel p = new JPanel();   
    //p.add(tableNames);   
       
       
    jlCodigoDe.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));           
    jlCodigoAte.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));           
       
    //Adicionando um parametro para minha busca   
    jtfNome.setText("Digite o parametro para a Busca");   
    jtfCodigoDe.setText("0000");   
    jtfCodigoAte.setText("9999");   

       
    jbBuscar.setText("Buscar");   

    //Adicionando o Label de minha aplicacao   
    p.add(jlCodigoDe);   
    p.add(jtfCodigoDe);   
    p.add(jlCodigoAte);   
    p.add(jtfCodigoAte);   
    //p.add(jtfNome);   
       
       
    contentPane.add(p, "North");   
       
    p.add(jbBuscar);   
       
       
    try {   
        Class.forName("com.mysql.jdbc.Driver");   
        // force loading of driver   
        String url = "jdbc:mysql://localhost:3306/spherecrims";   
        String user = "root";   
        String password = "";   
        con = DriverManager.getConnection(url, user,   
            password);   
        if (SCROLLABLE)   
            stmt = con.createStatement(   
                ResultSet.TYPE_SCROLL_INSENSITIVE,   
                ResultSet.CONCUR_READ_ONLY);   
        else   
            stmt = con.createStatement();   
        DatabaseMetaData md = con.getMetaData();   
        ResultSet mrs = md.getTables(null, null, null,   
            new String[] { "TABLE" });   
        while (mrs.next())   
            tableNames.addItem(mrs.getString(3));   
        mrs.close();   
    } catch(ClassNotFoundException e) {   
        System.out.println("Error " + e);   
    } catch(SQLException e) {   
        System.out.println("Error " + e);   
    }   
}   
   
public void actionPerformed(ActionEvent evt) {   
    if (evt.getSource() == jbBuscar) {   
        setBounds(200,200,600,(20*tableNames.getMaximumRowCount())+80);   
 //       jtfCodigoDe.setSize(180,20);   
           
        if (scrollPane != null)   
            getContentPane().remove(scrollPane);   
        try {   
            String tableName   
                = (String)tableNames.getSelectedItem();   
            if (rs != null) rs.close();   
            //      String query = "SELECT concat(chave, '-', codigo) AS Chave, nome AS Nome FROM tb_cadastrarcriminosos where codigo";   
            String query = "SELECT concat(chave, '-', codigo) AS Chave, nome AS Nome FROM tb_cadastrarcriminosos where codigo between " +jtfCodigoDe.getText()+" and " + jtfCodigoAte.getText();
//                String query = "SELECT * FROM " + tableName; NESTE TRECHO AQUI EU PEGAVA E SELECIONAVA AS TABELA POR UM CHECK BOX

//                String query = "SELECT * FROM " + tableName;

rs = stmt.executeQuery(query);

if (SCROLLABLE)

model = new ScrollingResultSetTableModel(rs);

else

model = new CachingResultSetTableModel(rs);
JTable table = new JTable(model);   
            scrollPane = new JScrollPane(table);   
            getContentPane().add(scrollPane, "Center");   
            pack();   
            doLayout();   
            jtfCodigoAte.setSize(50,20);   
               
        } catch(SQLException e) {   
            System.out.println("Error " + e);   
        }   
    }   
       
    if (evt.getSource() == tableNames) {  // show the selected table from the combo box   
    /*  
        jtfNome.setSize(180,20);  

        if (scrollPane != null)  
            getContentPane().remove(scrollPane);  
        try {  
            String tableName  
                = (String)tableNames.getSelectedItem();  
            if (rs != null) rs.close();  
              String query = "SELECT concat(chave, '-', codigo) AS Chave, nome AS Nome FROM tb_cadastrarcriminosos where codigo";
//                String query = “SELECT concat(chave, ‘-’, codigo) AS Chave, nome AS Nome FROM tb_cadastrarcriminosos where codigo = " +jtfNome.getText()+”";

//                String query = "SELECT * FROM " + tableName; NESTE TRECHO AQUI EU PEGAVA E SELECIONAVA AS TABELA POR UM CHECK BOX

//                String query = "SELECT * FROM " + tableName;

rs = stmt.executeQuery(query);

if (SCROLLABLE)

model = new ScrollingResultSetTableModel(rs);

else

model = new CachingResultSetTableModel(rs);
JTable table = new JTable(model);  
            scrollPane = new JScrollPane(table);  
            getContentPane().add(scrollPane, "Center");  
            pack();  
            doLayout();  
        } catch(SQLException e) {  
            System.out.println("Error " + e);  
        }  
     */   
    }   
}   
   
private JScrollPane scrollPane;   
private ResultSetTableModel model;   
private JComboBox tableNames;   
private JButton nextButton;   
private JButton previousButton;   
private ResultSet rs;   
private Connection con;   
private Statement stmt;   
public JButton jbBuscar;   
public JTextField jtfNome;   
   
public JTextField jtfCodigoDe;   
public JTextField jtfCodigoAte;   
   
public JLabel jlCodigoDe;   
public JLabel jlCodigoAte;   

private static boolean SCROLLABLE = false;   
// set to true if your database supports scrolling cursors

}
/*

  • ResultsetTable.java
  • Created on 19 de Novembro de 2007, 08:14
  • To change this template, choose Tools | Template Manager
  • and open the template in the editor.
    */

package listagems;

/**
*

  • @author kleber
    */
import java.awt.<em>;

import java.awt.event.</em>;

import java.sql.<em>;

import java.util.</em>;

import javax.swing.<em>;

import javax.swing.table.</em>;

public class ResultsetTable {

public static void main(String[] args) {
    JFrame frame = new ResultSetFrame();
    frame.show();
}

}

/* this class is the base class for the scrolling and the
caching result set table model. It stores the result set
and its metadata.
*/

abstract class ResultSetTableModel extends AbstractTableModel {

public ResultSetTableModel(ResultSet aResultSet) {

rs = aResultSet;

try {

rsmd = rs.getMetaData();

} catch(SQLException e) {

System.out.println("Error " + e);

}

}
public String getColumnName(int c) {
    try {
        return rsmd.getColumnName(c + 1);
    } catch(SQLException e) {
        System.out.println("Error " + e);
        return "";
    }
}

public int getColumnCount() {
    try {
        return rsmd.getColumnCount();
    } catch(SQLException e) {
        System.out.println("Error " + e);
        return 0;
    }
}

protected ResultSet getResultSet() {
    return rs;
}

private ResultSet rs;
private ResultSetMetaData rsmd;

}

/* this class uses a scrolling cursor, a JDBC 2 feature
*/

class ScrollingResultSetTableModel extends ResultSetTableModel {

public ScrollingResultSetTableModel(ResultSet aResultSet) {

super(aResultSet);

}
public Object getValueAt(int r, int c) {
    try {
        ResultSet rs = getResultSet();
        rs.absolute(r + 1);
        return rs.getObject(c + 1);
    } catch(SQLException e) {
        System.out.println("Error " + e);
        return null;
    }
}

public int getRowCount() {
    try {
        ResultSet rs = getResultSet();
        rs.last();
        return rs.getRow();
    } catch(SQLException e) {
        System.out.println("Error " + e);
        return 0;
    }
}

}

/* this class caches the result set data; it can be used
if scrolling cursors are not supported
*/

class CachingResultSetTableModel extends ResultSetTableModel {

public CachingResultSetTableModel(ResultSet aResultSet) {

super(aResultSet);

try {

cache = new ArrayList();

int cols = getColumnCount();

ResultSet rs = getResultSet();
/* place all data in an array list of Object[] arrays
        We don't use an Object[][] because we don't know
        how many rows are in the result set
      */
        
        while (rs.next()) {
            Object[] row = new Object[cols];
            for (int j = 0; j &lt; row.length; j++)
                row[j] = rs.getObject(j + 1);
            cache.add(row);
        }
    } catch(SQLException e) {
        System.out.println("Error " + e);
    }
}

public Object getValueAt(int r, int c) {
    if (r &lt; cache.size())
        return ((Object[])cache.get(r))[c];
    else
        return null;
}

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

private ArrayList cache;

}

class ResultSetFrame extends JFrame

implements ActionListener {

public ResultSetFrame() {

setTitle(Resultado da Pesquisa);

setBounds(200,200,600,80);
setResizable(false);
    
    //setExtendedState(this.MAXIMIZED_BOTH);
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    } );
    
  /* find all tables in the database and add them to
     a combo box
   */
    
    Container contentPane = getContentPane();
    tableNames = new JComboBox();

    jlCodigoDe = new JLabel("Buscar código de:", SwingConstants.RIGHT);        
    jlCodigoAte = new JLabel("Ate:", SwingConstants.RIGHT);        
    
    jbBuscar = new JButton();

    jtfNome = new JTextField();
    jtfCodigoDe = new JTextField();
    jtfCodigoAte = new JTextField();
    jtfCodigoAte.setSize(20,10);
    
    
    
    jtfCodigoDe.addActionListener(this);
    jtfCodigoAte.addActionListener(this);
        
    jtfNome.addActionListener(this);
    jbBuscar.addActionListener(this);
    
    
    tableNames.addActionListener(this);
    JPanel p = new JPanel();
    //p.add(tableNames);
    
    
    jlCodigoDe.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));        
    jlCodigoAte.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));        
    
    //Adicionando um parametro para minha busca
    jtfNome.setText("Digite o parametro para a Busca");
    jtfCodigoDe.setText("0000");
    jtfCodigoAte.setText("9999");

    
    jbBuscar.setText("Buscar");

    //Adicionando o Label de minha aplicacao
    p.add(jlCodigoDe);
    p.add(jtfCodigoDe);
    p.add(jlCodigoAte);
    p.add(jtfCodigoAte);
    //p.add(jtfNome);
    
    
    contentPane.add(p, "North");
    
    p.add(jbBuscar);
    
    
    try {
        Class.forName("com.mysql.jdbc.Driver");
        // force loading of driver
        String url = "jdbc:mysql://localhost:3306/spherecrims";
        String user = "root";
        String password = "";
        con = DriverManager.getConnection(url, user,
            password);
        if (SCROLLABLE)
            stmt = con.createStatement(
                ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        else
            stmt = con.createStatement();
        DatabaseMetaData md = con.getMetaData();
        ResultSet mrs = md.getTables(null, null, null,
            new String[] { "TABLE" });
        while (mrs.next())
            tableNames.addItem(mrs.getString(3));
        mrs.close();
    } catch(ClassNotFoundException e) {
        System.out.println("Error " + e);
    } catch(SQLException e) {
        System.out.println("Error " + e);
    }
}

public void actionPerformed(ActionEvent evt) {
    if (evt.getSource() == jbBuscar) {
        setBounds(200,200,600,(20*tableNames.getMaximumRowCount())+80);
 //       jtfCodigoDe.setSize(180,20);
        
        if (scrollPane != null)
            getContentPane().remove(scrollPane);
        try {
            String tableName
                = (String)tableNames.getSelectedItem();
            if (rs != null) rs.close();
            //      String query = "SELECT concat(chave, '-', codigo) AS Chave, nome AS Nome FROM tb_cadastrarcriminosos where codigo";
            String query = "SELECT concat(chave, '-', codigo) AS Chave, nome AS Nome FROM tb_cadastrarcriminosos where codigo between " +jtfCodigoDe.getText()+" and " + jtfCodigoAte.getText();
//                String query = "SELECT * FROM " + tableName; NESTE TRECHO AQUI EU PEGAVA E SELECIONAVA AS TABELA POR UM CHECK BOX

//                String query = "SELECT * FROM " + tableName;

rs = stmt.executeQuery(query);

if (SCROLLABLE)

model = new ScrollingResultSetTableModel(rs);

else

model = new CachingResultSetTableModel(rs);
JTable table = new JTable(model);
            scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane, "Center");
            pack();
            doLayout();
            jtfCodigoAte.setSize(50,20);
            
        } catch(SQLException e) {
            System.out.println("Error " + e);
        }
    }
    
    if (evt.getSource() == tableNames) {  // show the selected table from the combo box
    /*
        jtfNome.setSize(180,20);

        if (scrollPane != null)
            getContentPane().remove(scrollPane);
        try {
            String tableName
                = (String)tableNames.getSelectedItem();
            if (rs != null) rs.close();
              String query = "SELECT concat(chave, '-', codigo) AS Chave, nome AS Nome FROM tb_cadastrarcriminosos where codigo";
//                String query = “SELECT concat(chave, ‘-’, codigo) AS Chave, nome AS Nome FROM tb_cadastrarcriminosos where codigo = " +jtfNome.getText()+”";

//                String query = "SELECT * FROM " + tableName; NESTE TRECHO AQUI EU PEGAVA E SELECIONAVA AS TABELA POR UM CHECK BOX

//                String query = "SELECT * FROM " + tableName;

rs = stmt.executeQuery(query);

if (SCROLLABLE)

model = new ScrollingResultSetTableModel(rs);

else

model = new CachingResultSetTableModel(rs);
JTable table = new JTable(model);
            scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane, "Center");
            pack();
            doLayout();
        } catch(SQLException e) {
            System.out.println("Error " + e);
        }
     */
    }
}

private JScrollPane scrollPane;
private ResultSetTableModel model;
private JComboBox tableNames;
private JButton nextButton;
private JButton previousButton;
private ResultSet rs;
private Connection con;
private Statement stmt;
public JButton jbBuscar;
public JTextField jtfNome;

public JTextField jtfCodigoDe;
public JTextField jtfCodigoAte;

public JLabel jlCodigoDe;
public JLabel jlCodigoAte;

private static boolean SCROLLABLE = false;
// set to true if your database supports scrolling cursors

}

Ela esta funcionando corretamente, porem nao sei como fazer na hora que o individuo clicar ele ir para um formulario e receber estes dados, Grato estou no aguardo.

2 Respostas

S

ola,
tente fazer assim:

private void tabMouseClicked&#40;java.awt.event.MouseEvent evt&#41; &#123;                                 
        int linha_num=evt.getSelectedRow&#40;&#41;;
    &#125;

ai vc pegando o numero da linha selecionada, pega os dados referentes aquela linha e coloca num outro formulario…
flw

S

Olá amigo Sephil, nao entrou e nem me enviou nenhuma mensagem, o que deve ser estou utilizando junto com o jCroll / JTable mas adiciono um System.out… para ver se pelo menos me mostre alguma mensagem na hora de algum clique mas nem fungou, se puder me ajudar agradeco.

//Evento que deleta os registros da tabela
        int opcao = JOptionPane.showConfirmDialog&#40;this, "Deseja relamente deletar o registro?",
            "Excluindo", JOptionPane.YES_NO_CANCEL_OPTION&#41;;
        
        if&#40;opcao == 0&#41;&#123;
            
            //Obter a linha selecionada
            int x = jTable1.getSelectedRow&#40;&#41;;
            
            //Obetem a celula selecionada para que possa fazer o delete, dependendo de como estiver o select tem que editar o pornteiro
            String item = &#40;String&#41;jTable1.getModel&#40;&#41;.getValueAt&#40;x,1&#41;;
            System.out.println&#40;item&#41;;
            
            try&#123;
                String sqlDeleta = "DELETE FROM tb_cadastrarcriminosos where codigo =" +item;
                statement.executeUpdate&#40;sqlDeleta&#41;;
                System.out.println&#40;sqlDeleta&#41;;
                
                
                //Posicao na tabela
                System.out.println&#40;x&#41;;
                //Valor do Sql
                System.out.println&#40;item&#41;;
                
            &#125;catch&#40;SQLException erro&#41;&#123;
                
                System.out.println&#40;erro.getMessage&#40;&#41;&#41;;
                // Atualiza a tabela
                jTable1.setModel&#40;setModelo&#40;&#41;&#41;;
                
            &#125;
            
            //jtfCodigoDe.setText&#40;"0"&#41;;
            //jtfCodigoAte.setText&#40;"999999"&#41;;
            
            //Dando um refresh na tabela
            jTable1.setModel&#40;setModelo&#40;&#41;&#41;;
            
            //Fazendo com que os campos permanecem iquais - ok
            jTable1.setColumnModel&#40;setColunas&#40;&#41;&#41;;
            
        &#125;

Esta parte que deleta o registro na hora que eu mando mostrar o item ele me retorna o que eu quero mas nao quero na funcao deletar, eu quero so clicar na linha e me chamar o item para que eu guarde em uma var, Grato.

Criado 20 de novembro de 2007
Ultima resposta 22 de nov. de 2007
Respostas 2
Participantes 2