How to display query result in a JtextArea within a JtextArea

-1

How do I display data from a query in a database within a JtextArea? I have done all my Listing method (which is in the class CarroDAO), and I want it to show the data inside the textArea (which is in the Screen class)

follow the code:

DAO Car class with list method:

@Override
public ArrayList<Carro> listar() {

    ArrayList<Carro> carros= new ArrayList<Carro>();
    String sql="select * from carro";

try(Connection con= new ConnectionFactory().getConnection()){

    PreparedStatement ps= con.prepareStatement(sql);

    ResultSet rs= null;

    rs=ps.executeQuery();

    while(rs.next()) {

        Carro c= new Carro();

        //pegando os dados da tabela
        c.setId(rs.getInt("id"));
        c.setMarca(rs.getString("marca"));
        c.setModelo(rs.getString("modelo"));
        c.setCor(rs.getString("cor"));
        c.setPlaca(rs.getString("placa"));

        carros.add(c);
    }   

    ps.close();
    rs.close();

}catch(SQLException e){

    JOptionPane.showMessageDialog(null, "Erro ao realziar consulta:"+e, "ERROR", JOptionPane.ERROR_MESSAGE);
    throw new RuntimeException(e);

}
    return carros;
}

Screen Class with JtextArea:

JTextArea textArea = new JTextArea();


    //Jscrollpane:
    //colocando o text area dentro do ScrollPane
    jspane= new JScrollPane(textArea);
    jspane.setBounds(286, 48, 162, 170);
    contentPane.add(jspane);
    
asked by anonymous 02.11.2017 / 18:20

1 answer

1

After starting the component, just create a loop that will scan the entire list returned by your method, similar to the below:

JTextArea textArea = new JTextArea();


//Jscrollpane:
//colocando o text area dentro do ScrollPane
jspane= new JScrollPane(textArea);
jspane.setBounds(286, 48, 162, 170);
contentPane.add(jspane);

ArrayList<Carro> carros = dao.listar();

for(Carro c :  carros) {
   textArea.append(String.valueOf(c.getId()));
   textArea.append(System.lineSeparator());
   textArea.append(c.getMarca());
   textArea.append(System.lineSeparator());
   textArea.append(c.getModelo());
   textArea.append(System.lineSeparator());
   textArea.append(c.getCor());
   textArea.append(System.lineSeparator());
   textArea.append(c.getPlaca());
   textArea.append("===========");
   textArea.append(System.lineSeparator());
}

The System.lineSeparator() method inserts a line break between each property.

Remembering that dao must be an already started instance of its CarroDAO class where the listar() method is.

    
02.11.2017 / 18:54