To show database query result within a jtextarea

Asked

Viewed 455 times

-1

How do I display the data of a query in a database, within a Jtextarea? I did all my list method (which is in the Carrodao class), and I want it to show the data inside the textarea (which is in the Canvas class)

follows the code:

Class Car DAO with the 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);

1 answer

1


After starting the component, simply create a loop that will scan the entire list returned by your method, similar to the one 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 method System.lineSeparator() inserts a line break between each property.

Remembering that dao must be an instance already started from your class CarroDAO where the method listar() is found.

  • @Viny_hidan see the edition I made, now it is very clear how you can do.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.