Pagina 1 di 2 1 2 ultimoultimo
Visualizzazione dei risultati da 1 a 10 su 11
  1. #1

    Data di nascita ed età

    Buongiorno,

    il mio problema consiste nel cercare di far calcolare l'età e farla comparire in un apposita TextField costruita quando l'utente digita la Data di nascita nel pannello costruito.
    Vi riporto parte del codice (non completamente corretto) sviluppato fino ad ora (mi scuso per il disordine).

    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.text.ParseException;

    public class Quest extends JPanel
    implements ActionListener {

    private JTextField nameField;
    private JTextField cognomeField;
    private JTextField dataField;
    public String Data_nascita;
    private JTextField eta;
    private JTextField Data_attuale;

    public Quest (JFrame f) throws ParseException {

    nameField = new JTextField(20);
    cognomeField = new JTextField(20);
    dataField = new JTextField(4);
    eta=new JTextField(3);
    Data_attuale = new JTextField(10);

    JLabel label = new JLabel("Nome");
    label.setLabelFor(nameField);

    JLabel label1 = new JLabel("Cognome");
    label.setLabelFor(cognomeField);

    JLabel label3 = new JLabel("Data di nascita");
    label3.setLabelFor(dataField);

    JLabel label4 = new JLabel("Eta");
    label4.setLabelFor(eta);

    JLabel label5 = new JLabel("Data attuale");
    Data_attuale.setText("04/01/2010");
    label5.setLabelFor(Data_attuale);


    JPanel labels = new JPanel(new GridLayout(5, 1));
    labels.add(label);
    labels.add(label1);
    labels.add(label3);
    labels.add(label4);
    labels.add(label5);

    JPanel fields = new JPanel(new GridLayout(5, 1));
    fields.add(nameField);
    fields.add(cognomeField);
    fields.add(dataField);
    fields.add(eta);
    fields.add(Data_attuale);

    Box group = Box.createHorizontalBox();
    group.add(labels);
    group.add(fields);
    JPanel container = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    container.add(group);

    Data_nascita= dataField.getText();

    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    String Dataattuale = formatter.format(Data_attuale);
    String Datanascita = formatter.format(Data_nascita);


    Calendar cal=Calendar.getInstance();
    cal.setTime(Data_nasc);

    diffDates(Data_odierna,Data_nasc);

    add(container);


    }

    public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();

    }

    protected void resetFocus() {
    nameField.requestFocusInWindow();
    cognomeField.requestFocusInWindow();
    }

    private static void createAndShowGUI() throws ParseException {
    //Create and set up the window.
    JFrame frame = new JFrame("Questionario");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);

    //Create and set up the content pane.
    final Quest newContentPane = new Quest(frame);
    newContentPane.setOpaque(false); //content panes must be opaque
    frame.setContentPane(newContentPane);

    //Make sure the focus goes to the right component
    //whenever the frame is initially given the focus.
    frame.addWindowListener(new WindowAdapter() {
    public void windowActivated(WindowEvent e) {
    newContentPane.resetFocus();
    }
    });

    //Display the window.
    frame.pack();
    frame.setVisible(true);

    }

    public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.


    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    try {
    //Turn off metal's use of bold fonts
    UIManager.put("swing.boldMetal", Boolean.TRUE);
    createAndShowGUI();
    } catch (ParseException ex) {
    Logger.getLogger(Quest.class.getName()).log(Level. SEVERE, null, ex);
    }
    }
    });
    };

    public static int numDaysPreviousMonth (Calendar cal)
    {
    Calendar c = (Calendar)cal.clone ();
    c.roll (Calendar.MONTH, -1);
    return c.getActualMaximum (Calendar.DAY_OF_MONTH);
    }

    public DiffDate diffDates (Calendar beforeDate, Calendar afterDate)
    {
    int carryDay = 0;
    int carryMonth = 0;
    int diffday = afterDate.get(Calendar.DAY_OF_MONTH) - beforeDate.get(Calendar.DAY_OF_MONTH);
    if (diffday < 0)
    {
    diffday += numDaysPreviousMonth (afterDate);
    carryDay = 1;
    }

    int diffmonth = afterDate.get(Calendar.MONTH) - beforeDate.get(Calendar.MONTH) - carryDay;
    if (diffmonth < 0)
    {
    diffmonth += 12;
    carryMonth = 1;
    }
    int diffyear = afterDate.get(Calendar.YEAR) - beforeDate.get(Calendar.YEAR) - carryMonth;
    return new DiffDate (diffyear, diffmonth, diffday);
    }


    }

    In particolare il problema è rappresentato dal fatto che il richiedere la data odierna mi causa delle eccezioni che non riesco a capire.
    Ho già provato a leggere il tutorial java su Calendar e Gregorian Calendar però non sono riuscito ad andare oltre a quello che ho fatto.
    Il tutto è finalizzato a creare una sorta di questionario con Nome,Cognome, Data di Nascita e altri dati in cui però voglio che l'età sia calcolata e non scritta da chi inserisce i dati.
    Ringrazio anticipatamente chi avrà voglia di rispondermi.

    Saluti

  2. #2
    Utente di HTML.it L'avatar di Pastore12
    Registrato dal
    Oct 2008
    Messaggi
    1,051
    Il codice va messo tra i tag [ code] e [/code ] onde agevolarne la lettura.

    Se il codice ti genera delle exception che per te sono incomprensibili, potrebbero essere comprensibili invece per qualcun altro, quindi sei pregato di fornirle.
    "Ethics are to me something private. Whenever you use it as an argument for why somebody_else should do something, you’re no longer being ethical, you’re just being a sanctimonious dick-head"
    Linus Torvalds

  3. #3
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013

    Re: Data di nascita ed età

    Originariamente inviato da alsign1893
    [...]
    Vi riporto parte del codice (non completamente corretto) sviluppato fino ad ora (mi scuso per il disordine).
    Riordiniamolo (tag CODE)
    codice:
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.text.ParseException;
    
    public class Quest extends JPanel
         implements ActionListener {
        
        private JTextField nameField;
        private JTextField cognomeField;
        private JTextField dataField;
        public String Data_nascita;
        private JTextField eta;
        private JTextField Data_attuale;
    
        public Quest (JFrame f) throws ParseException {
                    
            nameField = new JTextField(20);
            cognomeField = new JTextField(20);
            dataField = new JTextField(4);
            eta=new JTextField(3);
            Data_attuale = new JTextField(10);
    
            JLabel label = new JLabel("Nome");
            label.setLabelFor(nameField);
    
            JLabel label1 = new JLabel("Cognome");
            label.setLabelFor(cognomeField);
    
            JLabel label3 = new JLabel("Data di nascita");
            label3.setLabelFor(dataField);
    
            JLabel label4 = new JLabel("Eta");
            label4.setLabelFor(eta);
    
            JLabel label5 = new JLabel("Data attuale");
            Data_attuale.setText("04/01/2010");
            label5.setLabelFor(Data_attuale);
    
    
            JPanel labels = new JPanel(new GridLayout(5, 1));
            labels.add(label);
            labels.add(label1);
            labels.add(label3);
            labels.add(label4);
            labels.add(label5);
    
            JPanel fields = new JPanel(new GridLayout(5, 1));
            fields.add(nameField);
            fields.add(cognomeField);
            fields.add(dataField);
            fields.add(eta);
            fields.add(Data_attuale);
    
            Box group = Box.createHorizontalBox();
            group.add(labels);
            group.add(fields);
            JPanel container = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            container.add(group);
    
            Data_nascita= dataField.getText();
                    
            SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
            String Dataattuale = formatter.format(Data_attuale);
            String Datanascita = formatter.format(Data_nascita);
    
                   
            Calendar cal=Calendar.getInstance();
            cal.setTime(Data_nasc);
    
            diffDates(Data_odierna,Data_nasc);
            
            add(container);
            
    
          }
    
            public void actionPerformed(ActionEvent e) {
            String cmd = e.getActionCommand();
    
            }
    
        protected void resetFocus() {
            nameField.requestFocusInWindow();
            cognomeField.requestFocusInWindow();
        }
    
        private static void createAndShowGUI() throws ParseException {
            //Create and set up the window.
            JFrame frame = new JFrame("Questionario");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
            //Create and set up the content pane.
            final Quest newContentPane = new Quest(frame);
            newContentPane.setOpaque(false); //content panes must be opaque
            frame.setContentPane(newContentPane);
    
            //Make sure the focus goes to the right component
            //whenever the frame is initially given the focus.
            frame.addWindowListener(new WindowAdapter() {
                public void windowActivated(WindowEvent e) {
                    newContentPane.resetFocus();
                }
            });
    
            //Display the window.
            frame.pack();
            frame.setVisible(true);
    
        }
    
        public static void main(String[] args) {
            //Schedule a job for the event dispatch thread:
            //creating and showing this application's GUI.
    
    
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    try {
                        //Turn off metal's use of bold fonts
                        UIManager.put("swing.boldMetal", Boolean.TRUE);
                        createAndShowGUI();
                    } catch (ParseException ex) {
                        Logger.getLogger(Quest.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    } 
                });
            };
    
        public static int numDaysPreviousMonth (Calendar cal)
    	{
    		Calendar c = (Calendar)cal.clone ();
    		c.roll (Calendar.MONTH, -1);
    		return c.getActualMaximum (Calendar.DAY_OF_MONTH);
    	}
    
    	public DiffDate diffDates (Calendar beforeDate, Calendar afterDate)
    	{
    		int carryDay = 0;
    		int carryMonth = 0;
    		int diffday = afterDate.get(Calendar.DAY_OF_MONTH) -                     beforeDate.get(Calendar.DAY_OF_MONTH);
    		if (diffday < 0)
    		{
    			diffday += numDaysPreviousMonth (afterDate);
    			carryDay = 1;
    		}
    
    		int diffmonth = afterDate.get(Calendar.MONTH) - beforeDate.get(Calendar.MONTH) - carryDay;
    		if (diffmonth < 0)
    		{
    			diffmonth += 12;
    			carryMonth = 1;
    		}
    		int diffyear = afterDate.get(Calendar.YEAR) - beforeDate.get(Calendar.YEAR) - carryMonth;
    		return new DiffDate (diffyear, diffmonth, diffday);
    	}
    
            
    }
    poi come ti ha suggerito Pastore12: non puoi chiedere alla gente di copiarsi ed interpretarsi 200 righe di codice senza essere un minimo specifico riguardo agli errori che saltano fuori.

    di sicuro, qualche stringa non viene inizializzata e quindi non è possibile parsarla e formattarla. che altro?
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  4. #4
    Scusa hai ragione.
    Lo riporto in maniera corretta e aggiungo giustamente le eccezioni.

    codice:
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.text.ParseException;
    
    public class Quest extends JPanel
    implements ActionListener {
    
    private JTextField nameField;
    private JTextField cognomeField;
    private JTextField dataField;
    public String Data_nascita;
    private JTextField eta;
    private JTextField Data_attuale;
    
    public Quest (JFrame f) throws ParseException {
    
    nameField = new JTextField(20);
    cognomeField = new JTextField(20);
    dataField = new JTextField(4);
    eta=new JTextField(3);
    Data_attuale = new JTextField(10);
    
    JLabel label = new JLabel("Nome");
    label.setLabelFor(nameField);
    
    JLabel label1 = new JLabel("Cognome");
    label.setLabelFor(cognomeField);
    
    JLabel label3 = new JLabel("Data di nascita");
    label3.setLabelFor(dataField);
    
    JLabel label4 = new JLabel("Eta");
    label4.setLabelFor(eta);
    
    JLabel label5 = new JLabel("Data attuale");
    Data_attuale.setText("04/01/2010");
    label5.setLabelFor(Data_attuale);
    
    
    JPanel labels = new JPanel(new GridLayout(5, 1));
    labels.add(label);
    labels.add(label1);
    labels.add(label3);
    labels.add(label4);
    labels.add(label5);
    
    JPanel fields = new JPanel(new GridLayout(5, 1));
    fields.add(nameField);
    fields.add(cognomeField);
    fields.add(dataField);
    fields.add(eta);
    fields.add(Data_attuale);
    
    Box group = Box.createHorizontalBox();
    group.add(labels);
    group.add(fields);
    JPanel container = new JPanel(new FlowLayout(FlowLayout.RIGHT));
    container.add(group);
    
    Data_nascita= dataField.getText();
    
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    String Dataattuale = formatter.format(Data_attuale);
    String Datanascita = formatter.format(Data_nascita);
    
    
    Calendar cal=Calendar.getInstance();
    cal.setTime(Data_nasc);
    
    diffDates(Data_odierna,Data_nasc);
    
    add(container);
    
    
    }
    
    public void actionPerformed(ActionEvent e) {
    String cmd = e.getActionCommand();
    
    }
    
    protected void resetFocus() {
    nameField.requestFocusInWindow();
    cognomeField.requestFocusInWindow();
    }
    
    private static void createAndShowGUI() throws ParseException {
    //Create and set up the window.
    JFrame frame = new JFrame("Questionario");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    //Create and set up the content pane.
    final Quest newContentPane = new Quest(frame);
    newContentPane.setOpaque(false); //content panes must be opaque
    frame.setContentPane(newContentPane);
    
    //Make sure the focus goes to the right component
    //whenever the frame is initially given the focus.
    frame.addWindowListener(new WindowAdapter() {
    public void windowActivated(WindowEvent e) {
    newContentPane.resetFocus();
    }
    });
    
    //Display the window.
    frame.pack();
    frame.setVisible(true);
    
    }
    
    public static void main(String[] args) {
    //Schedule a job for the event dispatch thread:
    //creating and showing this application's GUI.
    
    
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    try {
    //Turn off metal's use of bold fonts
    UIManager.put("swing.boldMetal", Boolean.TRUE);
    createAndShowGUI();
    } catch (ParseException ex) {
    Logger.getLogger(Quest.class.getName()).log(Level.SEVERE, null, ex);
    }
    } 
    });
    };
    
    public static int numDaysPreviousMonth (Calendar cal)
    {
    Calendar c = (Calendar)cal.clone ();
    c.roll (Calendar.MONTH, -1);
    return c.getActualMaximum (Calendar.DAY_OF_MONTH);
    }
    
    public DiffDate diffDates (Calendar beforeDate, Calendar afterDate)
    {
    int carryDay = 0;
    int carryMonth = 0;
    int diffday = afterDate.get(Calendar.DAY_OF_MONTH) - beforeDate.get(Calendar.DAY_OF_MONTH);
    if (diffday < 0)
    {
    diffday += numDaysPreviousMonth (afterDate);
    carryDay = 1;
    }
    
    int diffmonth = afterDate.get(Calendar.MONTH) - beforeDate.get(Calendar.MONTH) - carryDay;
    if (diffmonth < 0)
    {
    diffmonth += 12;
    carryMonth = 1;
    }
    int diffyear = afterDate.get(Calendar.YEAR) - beforeDate.get(Calendar.YEAR) - carryMonth;
    return new DiffDate (diffyear, diffmonth, diffday);
    }
    
    
    }
    Le eccezioni sono le seguenti:

    codice:
            at Quest.createAndShowGUI(Quest.java:130)
            at Quest.access$000(Quest.java:10)
            at Quest$2.run(Quest.java:157)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
            at  java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

  5. #5
    Utente di HTML.it L'avatar di Pastore12
    Registrato dal
    Oct 2008
    Messaggi
    1,051
    at Quest.createAndShowGUI(Quest.java:130)
    at Quest.access$000(Quest.java:10)
    at Quest$2.run(Quest.java:157)
    at java.awt.event.InvocationEvent.dispatch(Invocation Event.java:209)
    ...
    Darò una occhiata al codice sopra, ma questo è un pezzo dello stackTrace abbastanza inutile.
    L'eccezione la devi postare tutta, o almeno le righe in cui compaiono le tue classi.

    Esempio:

    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Array index out of range: 5
    at CertificateReader.test(CertificateReader.java:56)
    at Quest.createAndShowGUI(Quest.java:130)
    at Quest.access$000(Quest.java:10)
    at Quest$2.run(Quest.java:157)
    at java.awt.event.InvocationEvent.dispatch(Invocation Event.java:209)
    at ...
    La prima riga serve a capire cosa si è rotto, tutte le altre dove. Nella lista che ti ritrovi compare di sicuro anche una classe che hai scritto tu. Il numero a destra ti dice anche anche a che riga della tua classe è scoppiato il casino.
    "Ethics are to me something private. Whenever you use it as an argument for why somebody_else should do something, you’re no longer being ethical, you’re just being a sanctimonious dick-head"
    Linus Torvalds

  6. #6
    L'eccezione completa era quella che ho riportato.

    Ancor prima di rimodificare il codice sono comparse queste eccezioni sebbene nel programma non vi fosse a quel momento nessun errore di sintassi.

    Il tutto dopo aver aggiunto un po di codice relativo alla manipolazione delle date in particolare al tentativo di ottenere la data attuale alla quale secondo le mie intenzioni andrebbe sottratta poi la data che l'utente digita in un apposito TextField creato, il tutto per ottenere l'età della persona di cui si inseriscono i dati.

    Questa età vorrei poi fare sì che compaia in automatico in un altro TextField creato al momento in cui l'utente ha finito di digitare la data di nascita.

  7. #7
    Ho riscritto il codice in maniera più ordinata e comprensibile in questo modo:

    codice:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.util.*;
    
    public class Main implements ActionListener {
    public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
    public void run() {
    start();
    }
    });
    }
    private static void start() {
    
    JPanel labels = new JPanel(new GridLayout(4, 1));
    labels.add(new JLabel("Nome"));
    labels.add(new JLabel("Cognome"));
    labels.add(new JLabel("Data di nascita"));
    labels.add(new JLabel("Data attuale"));
    JTextField nameField = new JTextField(20);
    JTextField cognomeField = new JTextField(20);
    JTextField datanascita = new JTextField(10);
    JTextField dataattuale = new JTextField(10);
    
    JPanel fields = new JPanel(new GridLayout(4, 1));
    fields.add(nameField);
    fields.add(cognomeField);
    fields.add(datanascita);
    fields.add(dataattuale);
    Box group = Box.createHorizontalBox();
    group.add(labels);
    group.add(fields);
    
    JPanel container = new JPanel(new FlowLayout(FlowLayout.LEFT));
    container.add(group);
    JFrame window = new JFrame("Questionario");
    window.add(container);
    window.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    window.pack();
    window.setVisible(true);
    }
    public void actionPerformed(ActionEvent e) {
            String cmd = e.getActionCommand();
    
            }
    
    
    }
    e così non da nessun errore.

    Appena però inserisco le seguenti stringhe:

    codice:
    Calendar cal=Calendar.getInstance();
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    String Data = formatter.format(cal);
    
    dataattuale.setText(Data);
    dopo aver aggiunto le corrispondenti librerie richieste il programma, benchè non segnali particolari errori, sputa fuori le stesse eccezioni già riportate:

    codice:
    run:
    Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Cannot format given Object as a Date
            at java.text.DateFormat.format(DateFormat.java:281)
            at java.text.Format.format(Format.java:140)
            at Main.start(Main.java:39)
            at Main.access$000(Main.java:8)
            at Main$1.run(Main.java:12)
            at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
            at java.awt.EventDispatchThread.pumpOneEventForFilters    (EventDispatchThread.java:269)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
    BUILD SUCCESSFUL (total time: 1 second)
    il che mi fa pensare a qualche problema con la data.

  8. #8
    Utente di HTML.it
    Registrato dal
    Feb 2009
    Messaggi
    502
    Stai dando a SimpleDateFormat.format un oggetto che non è quello che lui si aspetta, ossia un Date.
    Leggi le javadoc su SimpleDateFormat e su Calendar che spiegano come fare.
    al volante son nervoso

  9. #9
    Utente di HTML.it
    Registrato dal
    Aug 2002
    Messaggi
    8,013
    Provo a darti un suggerimento in generale.

    La GUI va anche bene, adesso bisogna capire come interagiscono i vari ed eventuali elementi (o meglio, il loro contenuto) e in che ordine.

    Appuriamo che il formato data da usare sarà MM/dd/yyyy

    Ineccepibile.
    codice:
    SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
    Calendar non ti serve a niente.

    La data attuale, formattata secondo le tue esigenze la ottieni semplicemente applicando il formatter:

    codice:
    dataattuale.setText(formatter.format(new Date()));
    Personalmente renderei il campo dataattuale non modificabile. Oppure se non ti serve per qualche altra ragione, non lo inserirei proprio come campo nel form.

    A questo punto bisogna capire quel che succede: la data di nascita avrà un formato imposto - restiamo col formatter di cui sopra - e solo quello. I controlli da fare quando avverranno? Possibilmente quando il campo è stato compilato. Adesso ci sono svariati modi di verificare quando il campo è stato compilato. Il più rapido, senza tirare in ballo Spinners o maschere - anche se farebbero molto cool - è quello di appiccicare un listener al campo stesso e verificare quando viene modificato. Per tenere le cose semplici, io ci attaccherei un focuslistener, in particolare creandone uno ad hoc e riscrivendo solo il focusLost

    codice:
    private class MyFocusListener extends FocusAdapter {
    
            String datanascita, dataattuale;
            SimpleDateFormat formatter;
    
            public MyFocusListener(String dataattuale, SimpleDateFormat formatter) {
                this.formatter = formatter;
                this.dataattuale = dataattuale;
            }
    
            public void focusLost(FocusEvent fe) {            
                try {
                    datanascita = dataField.getText();
                    Date dn = formatter.parse(datanascita);
                    Date da = formatter.parse(dataattuale);
                    if (da.after(dn)) { //valida
                        int e = (int)((da.getTime()-dn.getTime())/(365.25d*3600*24*1000));
                        eta.setText(Integer.toString(e));
                    }
                    else {
                        dataField.setText("");
                        dataField.transferFocus();
                    }
                }
                catch (Exception e) {
                    dataField.setText("Wrong date format");
                    dataField.transferFocus();
                    e.printStackTrace();
                }            
            }
        }
    In definitiva il costruttore, utilizzando il tuo codice potrebbe diventare qualcosa del genere
    codice:
    public Quest (JFrame f) throws ParseException {
    
            nameField = new JTextField(20);
            cognomeField = new JTextField(20);
            dataField = new JTextField(4);
            eta=new JTextField(3);
            Data_attuale = new JTextField(10);
    
            JLabel label = new JLabel("Nome");
            label.setLabelFor(nameField);
    
            JLabel label1 = new JLabel("Cognome");
            label.setLabelFor(cognomeField);
    
            JLabel label3 = new JLabel("Data di nascita");
            label3.setLabelFor(dataField);
    
            JLabel label4 = new JLabel("Eta");
            label4.setLabelFor(eta);
    
            JLabel label5 = new JLabel("Data attuale");        
            label5.setLabelFor(Data_attuale);
    
    
            JPanel labels = new JPanel(new GridLayout(5, 1));
            labels.add(label);
            labels.add(label1);
            labels.add(label3);
            labels.add(label4);
            labels.add(label5);
    
            JPanel fields = new JPanel(new GridLayout(5, 1));
            fields.add(nameField);
            fields.add(cognomeField);
            fields.add(dataField);
            fields.add(eta);
            fields.add(Data_attuale);
    
            Data_nascita= dataField.getText();
    
            SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
            Data_attuale.setText(formatter.format(new Date()));
            Data_attuale.setEditable(false);
            eta.setEditable(false);
    
            dataField.addFocusListener(new MyFocusListener(Data_attuale.getText(), formatter));
    
            Box group = Box.createHorizontalBox();
            group.add(labels);
            group.add(fields);
            JPanel container = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            container.add(group);
            add(container);
    
    
          }
    <´¯)(¯`¤._)(¯`»ANDREA«´¯)(_.¤´¯)(¯`>
    "The answer to your question is: welcome to tomorrow"

  10. #10
    Moderatore di Programmazione L'avatar di LeleFT
    Registrato dal
    Jun 2003
    Messaggi
    17,320

    Moderazione

    Ti invito anche a prendere visione del Regolamento interno.

    I tag per il posting del codice si chiamano CODE e non "cod", inoltre, come qualunque altro tag BB vanno inseriti all'interno della parentesi quadre, altrimenti non vengono ovviamente interpretate.

    Il punto 6 del regolamento che ti ho linkato spiega nel dettaglio come usare questi tag.

    PS: cerca di dare anche un minimo di indentazione ai tuoi codici... ne benefici tu prima di tutto e chi deve metterci le mani in futuro (compresi gli utenti del forum che lo leggono e cercano di capire dov'è l'errore)


    Ciao.
    "Perchè spendere anche solo 5 dollari per un S.O., quando posso averne uno gratis e spendere quei 5 dollari per 5 bottiglie di birra?" [Jon "maddog" Hall]
    Fatti non foste a viver come bruti, ma per seguir virtute e canoscenza

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.