A teacher asked to develop a project (a CRUD of cars). I've done the insert, remove, list, and change part.
But the list part must be done by a thread (teacher's requirement), where it must list a car every 20 seconds and show in JTextArea
. My question is how to make the thread do this.
Follow the code:
% class of% to list. Note: I have not done anything in this class yet:
public class ThreadListar implements Runnable{
private int tempo;
public ThreadListar(int tempo) {
this.tempo=tempo;
Thread t1=new Thread(this);
t1.start();
}
@Override
public void run() {
try {
Thread.sleep(tempo);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Class Thread
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();
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;
}
Class CarroDAO
(swing) with the button and the action of listing and setting the data within Tela
:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Tela frame = new Tela();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Tela() {
JButton btnListar = new JButton("Listar");
btnListar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
CarroDAO dao1 = new CarroDAO();
ArrayList carros= dao1.listar();
for(Object o: carros) {
Carro c= (Carro) o;
textArea.append(String.valueOf("ID: "+c.getId()+"\n"));
textArea.append("Marca: "+c.getMarca()+"\n");
textArea.append("Modelo: "+c.getModelo()+"\n");
textArea.append("Cor: "+c.getCor()+"\n");
textArea.append("Placa: "+c.getPlaca()+"\n"+"\n");
textArea.append("=================");
}
}
});
btnListar.setBounds(234, 233, 89, 23);
contentPane.add(btnListar);
}
}
}