I'm having trouble determining if the user filled in a date field of type JDateChooser
, I'd like to do a validation to see if it's empty or not. I tried to do it by looking at the JDateChooser
documentation, it did not work very well, the only thing I thought was trying to get the date with a getDate () and see if it equals an empty "masquerade".
In practice, I saw that it is not correct, IDE already makes it clear that they are incompatible types ( getDate()
and equals()
)!
Here is the code I tried:
package calendar;
import com.toedter.calendar.JDateChooser;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class Jcalendar extends JFrame implements ActionListener
{
private final JDateChooser data = new JDateChooser();
private final JButton botao01 = new JButton("Salvar");
public JPanel jpBotoes = new JPanel();
public Jcalendar()
{
setSize(500, 300);
add(posicaoComponentes());
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
public JComponent posicaoComponentes()
{
JPanel jp = new JPanel();
jp.add(data);
data.setPreferredSize(new Dimension(100, 20));
getContentPane().add("North", data);
getContentPane().add("South", jpBotoes);
jpBotoes.setLayout(new GridLayout(1, 1));
adicionaBotao(botao01);
return jp;
}
private void adicionaBotao(JButton botao)
{
jpBotoes.add(botao);
botao.addActionListener(this);
}
public boolean vazio()
{
if(data.getDate().equals(" / / "))
{
return true;
}
else
{
return false;
}
}
@Override
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == botao01)
{
if( vazio() == true)
{
JOptionPane.showMessageDialog(null, "Inválido !");
}
else
{
JOptionPane.showMessageDialog(null, "Salvo !");
}
}
}
public static void main(String[] args)
{
EventQueue.invokeLater(() ->
{
Jcalendar c = new Jcalendar();
c.setVisible(true);
});
}
}