How to set focus on JDateChooser when frame is loaded in Swing?

3.2k views Asked by At

enter image description here

How to show focus on date chooser when frame is loaded?

  1. how could verify textfield that user can enter only date format and
  2. way how could i set focus on jdatechooser icon in swing.

code

private void jDateChooser2FocusGained(java.awt.event.FocusEvent evt) {
    // TODO add your handling code here:
        //JDateChooser2 jdc = new JDateChooser2("DD/MM/YYYY", true);
    //jDateChooser2.getDateEditor().getUiComponent().requestFocusInWindow();
  jDateChooser2.requestFocusInWindow();

}      

source code

public class welcome extends javax.swing.JFrame {

    public static final String DATE_FORMAT_NOW = "dd/MMM/YYYY ";
    Calendar cal = Calendar.getInstance();
    SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
    Date date = new Date();



    /**
     * Creates new form welcome
     */
    public welcome() {
        initComponents();



         sdf.setLenient(false);

         String dt = sdf.format(cal.getTime());
         System.out.println(dt);


            try  
            {  
                date = sdf.parse(dt); 
                 System.out.println(date);
            }  
            catch(ParseException pe)  
            {  
                System.out.println("pe: " + pe.getMessage());  
                Toolkit.getDefaultToolkit().beep();  
            }  
            jLabel3.setText(dt);
            jTextField1.setText(dt);
     }

private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {                                       
        // TODO add your handling code here:
   //   System.out.println("guihgio");
      if (evt.getKeyCode() == KeyEvent.VK_ENTER) {

            System.out.println("enter press key");


              this code is not working//

      char c = evt.getKeyChar();
      if (!((c >= '0') && (c <= '9') ||
         (c == KeyEvent.VK_BACK_SPACE) ||
         (c == KeyEvent.VK_DELETE) || (c == KeyEvent.VK_SLASH)))        
      {

           JOptionPane.showMessageDialog(null, "Please Enter Valid");
           evt.consume();
      }
  }

MY EVENT CODE private void jSpinner1KeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here: System.out.println("spiinejngyjgkur");

     if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        //password pwd = new password();
        //pwd.setVisible(true);










     jSpinner1.requestFocus();

       if (evt.getSource() == jSpinner1) //add
    {
        try {
            String host = "jdbc:mysql://localhost:3306/indospirit";
            String uName = "root";
            String uPass = "paras123";

            //Class.forName("com.mysql.jdbc.Driver").newInstance();
            java.sql.Driver d = new com.mysql.jdbc.Driver();

            Connection con = DriverManager.getConnection(host, uName, uPass);

            PreparedStatement ps;
                System.out.println("weww");

      ps = con.prepareStatement("INSERT INTO `log1`(`date`)VALUES('" + dateString + "')");

            int i = ps.executeUpdate();

            if (i > 0) {
                JOptionPane.showMessageDialog(null, "Record Added");
            } else {
                JOptionPane.showMessageDialog(null, "Record NOT Added");
            }
        } catch (SQLException ex) {
            //ex.printStackTrace();
            System.err.println(ex.toString());
        } catch (Exception ex1) {
            //ex1.printStackTrace();
            System.err.println(ex1.toString());
        }
    }

    try {
        String host = "jdbc:mysql://localhost:3306/indospirit";
        String uName = "root";
        String uPass = "paras123";

        //Class.forName("com.mysql.jdbc.Driver").newInstance();
        java.sql.Driver d = new com.mysql.jdbc.Driver();

        Connection con = DriverManager.getConnection(host, uName, uPass);
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * from `log1` ORDER BY `date` DESC limit 1");

        while (rs.next()) {

            int col = rs.getInt("id");
            String str = rs.getString("date");

            jLabel10.setText(str);

            System.out.println(col + " " + str + " ");

        }

    } catch (SQLException ex) {
        System.err.println(ex.toString());
    } catch (Exception ex1) {
        System.err.println(ex1.toString());
    }

         } 


        event not working

private void jSpinner1StateChanged(javax.swing.event.ChangeEvent evt) {
// TODO add your handling code here: System.out.println("gijjhbip"); System.out.println("Source: " + evt.getSource()); }

     how could  I check THAT date Enterd by user in date format in JFormattedTextField...please help  IN KEY PRESSED EVENT

       my code is here

private void jFormattedTextField1KeyPressed(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:

    System.out.println(evt.getKeyChar());

   if (evt.getKeyCode() == KeyEvent.VK_ENTER) {

       Date date = (Date) evt.getSource();
      if(!(date.equals(format)))
      {
          evt.consume();
      }
   }
3

There are 3 answers

9
Paul Samsotha On

"how could verify textfield that user can enter only date format and "

IMHO getting user input for a date is vary bad idea. Validating input will become a headache and is inefficient for the program, as the user can input any combination of character. Instead you could use a JSpinner using a DateListModel

See Spinner tutorial | SpinnerDateModel javadoc


But then again, why even allow for an input for today's date? That data can be retrieved any number of ways, other than getting the input from the user.


If you truly insist on doing your way, with the text field input and want to validate, you can always just catch a ParseException. but in such a situation, you would need to specify to the user exactly what format need to be inputted, and have some sort of notification for when the user input is not in a correct format or is not a real date.

SimpleDateFormat formatter = new SimplDateFormat(DATE_FORMAT_NOW);
String dateString = textField.getText();
Date date;
try {
    date = formatter.parse(dateString);
} catch (ParseException) {
    statusLabel.setText("Please enter a valid date");
    // or JOptionPane.showMessageDialog(null, "Please Enter a valid Date");
}

But again a problem is that the user can input an random date like some date in 2102. So I'd suggest either a JSpinner or an uneditable text field that just display today's date.


UPDATE try this

import java.util.Date; import java.text.SimpleDateFormat; import javax.swing.*;

public class SpinnerDateTest {

    public static void main(String[] args) {
        Date date = new Date();
        JSpinner spinner = new JSpinner();
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MMM//yyyy");
        String dateString = formatter.format(date);
        spinner.setModel(new SpinnerListModel(new String[]{dateString}));
        JOptionPane.showConfirmDialog(null, spinner, "Spinner:"
                ,JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

    }
}

Or using the SpinnerDateModel

public static void main(String[] args) {
    Date date = new Date();
    JSpinner spinner = new JSpinner();
    spinner.setModel(new SpinnerDateModel(date, null, null, Calendar.DAY_OF_WEEK));
    JOptionPane.showConfirmDialog(null, spinner, "Spinner:"
            ,JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

}
3
user3164607 On

I don't know what library you use, but why not try this jcalendar.

1st question: you can use JFormattedTextField, instand of JTextField.



    DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    DateFormatter formatter = new DateFormatter(format);  
    format.setLenient(false);  
    formatter.setAllowsInvalid(false);  
    formatter.setOverwriteMode(true);  
    JFormattedTextField formattedTextField = new JFormattedTextField(formatter);
    formattedTextField.setValue(new Date());
    formattedTextField.addKeyListener(new KeyAdapter() {

        @Override
        public void keyPressed(KeyEvent evt) {
            //System.out.println(evt.getKeyChar());
            //TODO
        }
    });

2nd question: the only way of getFocuse is to change the source code of JDateChoose; because the source code is



    protected JButton calendarButton;
    ...
    calendarButton = new JButton(icon) {

        public boolean isFocusable() {
            return false;
        }
    };

0
Marco Antonio Hermosilla On

You can use this for focus

jDateChooser.getDateEditor().getUiComponent().requestFocusInWindow();

If you want to control some event

jDateChooser.getDateEditor().getUiComponent().addKeyListener(new listenerClass());