Create method that takes typed time

Asked

Viewed 148 times

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?

  • @diegofm sorry, I was not clear with what I needed, I edited the question, now I believe it makes sense.

  • It can’t be like Date?

  • 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.

  • @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 !

1 answer

0


I made few changes to the code and worked smoothly, picking the time of the field in the click:

import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
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.SwingUtilities;
import javax.swing.text.MaskFormatter;

public class Hora extends JFrame {

    public static void main(String[] args) {

        SwingUtilities.invokeLater(() -> {
            Hora t = new Hora();
            t.setVisible(true);
        });
    }

    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 acao() {
        pegar.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                    System.out.println(new java.sql.Timestamp(sdf.parse(campoHora.getText()).getTime()));
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Não foi possível obter a hora!");
                    campoHora.setText("");
                    e.printStackTrace();
                }
            }
        });
    }
}

That way, he turns the guy Date for the format Timestamp, which can be saved in a similar field in your bank.

But I would use Jspinners, because then you can better control what is informed, without needing to stay dealing with whether the time is valid or not. If you are interested, here is a example of use of it with only hours, minutes and seconds.

  • I used the Spinner example, much better. Just one thing, it gives me an error, is that the formatting ? the error is: Exception in thread "AWT-Eventqueue-0" java.lang.Stackoverflowerror at sun.util.Calendar.BaseCalendar.getCalendarDateFromFixedDate(Basecalendar.java:432)

  • @Javinha sun,uitl,Calendar? Aren’t you using the wrong class? The right class is java.util.Calendar.

  • did like the example above, only differs is that as I created a component with the spinner ai do not need to place the field directly, so @Override public Object getValor() { Try , Simpledateformat sdft = new Simpledateformat("HH:mm:ss"); Return new java.sql.Timestamp(sdft.parse((String) getValor().getTime()); } catch (E) { Joptionpane.showMessageDialog(null, "Could not fetch Time!"); e.printStackTrace(); Return null; } }

  • @Javinha not seeing what you changed in your code or what you added, I can’t help you. The example there is simple, I had no problem running it. Some change you made is that must be generating this error.

  • https://pastebin.com/JxszV5i5

  • @Javinha because you are creating a method to call him in the action? Out you are calling this getValue recursively.

  • because if I use it on other screens after I use it. More is what caused the error ?

  • @Javinha you cannot call the method itself within it that way. It has entered an infinite loop, hence the error. Change the Return line to the following: return new java.sql.Timestamp(((Date)spinner.getModel().getValue()).getTime());

Show 3 more comments

Browser other questions tagged

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