0
How can I create a method that takes the time typed in a field?
It will take the contents of the field to save in the database. I use pojo and dao.
I made a very short example, what I need to do is a method that takes this String content and can save as Time or TimeStamp
at the bank.
what I tried to do was:
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Time;
import java.text.SimpleDateFormat;
import javax.swing.JButton;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.text.MaskFormatter;
public class Hora extends JFrame {
public static void main(String[] args) {
Hora t = new Hora();
t.setVisible(true);
}
private Pojo pojo = new Pojo();
JFormattedTextField campoHora = new JFormattedTextField();
JButton pegar = new JButton("Pegar");
public Hora() {
setSize(450, 300);
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
MaskFormatter mf = new MaskFormatter("##:##:##");
mf.install(campoHora);
} catch (Exception e) {
e.printStackTrace();
}
JPanel painel = new JPanel();
painel.add(campoHora);
campoHora.setPreferredSize(new Dimension(80, 22));
painel.add(pegar);
pegar.setPreferredSize(new Dimension(75, 22));
acao();
add(painel);
}
private void pegaPojo() {
pojo.setHora(campoHora.getValorTime());
}
private void acao() {
pegar.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
//campoHora.getValorTime();
}
});
}
private Time getValorTime() {
try {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.parse(getText());
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Não foi possível obter a hora!");
e.printStackTrace();
return null;
}
}
}
class Pojo {
private Time hora;
public Time getHora() {
return hora;
}
public void setHora(Time hora) {
this.hora = hora;
}
}
I didn’t understand your doubt. just a gettext() in the field for you to pick up his information. What difficulty are you having?
– user28595
@diegofm sorry, I was not clear with what I needed, I edited the question, now I believe it makes sense.
– Javinha
It can’t be like Date?
– user28595
I would do it using 3 spinners (one for hour, one for minute and one for second), because then you have much more control than is typed without having to do a lot of conversions and treatments.
– user28595
@diegofm I wanted to save only the hour, minutes and seconds. In the database the attributes are of type Timestamp, can give problem ? I’m open to suggestions, if you think it best, you’re welcome !
– Javinha