How can I create a method that takes the time typed in a field?
It will grab the contents of the field to save to the database. I use pojo and Dao.
I made a well-summed example, what I need to do is a method that takes this String content and can save as Time or TimeStamp
in the database.
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;
}
}