简体   繁体   中英

Calculate day of the week based on user input

I'm having trouble figuring out how make my program calculate the day of the week based on user input for month, day, year. Such as in this picture below. I have no clue on how to make it connect with the JTextField and the JComboBoxes. I truly appreciate anyones help with this. I know is I'm supposed to use:

Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25); int dayOfWeek = xmas.get(Calendar.DAY_OF_WEEK); // 6=Friday

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Calendar;
import java.util.GregorianCalendar;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JTextField;
import javax.swing.JTextArea;



public class DayOfWeek extends JFrame 
{

    private JPanel contentPane;
    private JTextField yearField;
    private JLabel dayOfW;

    /**
     * Launch the application.
     */
    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable()
        {
            public void run()
            {
                try
                {
                    DayOfWeek frame = new DayOfWeek();
                    frame.setVisible(true);
                } catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public DayOfWeek()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 230);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JLabel monthL = new JLabel("Month:");
        monthL.setBounds(10, 11, 46, 14);
        contentPane.add(monthL);

        JComboBox monthBox = new JComboBox();
        monthBox.setModel(new DefaultComboBoxModel(new String[] {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}));
        monthBox.setBounds(53, 8, 109, 20);
        contentPane.add(monthBox);

        JLabel dayL = new JLabel("Day: ");
        dayL.setBounds(172, 11, 31, 14);
        contentPane.add(dayL);

        JComboBox dayBox = new JComboBox();
        dayBox.setModel(new DefaultComboBoxModel(new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"}));
        dayBox.setBounds(203, 8, 53, 20);
        contentPane.add(dayBox);

        JLabel yearL = new JLabel("Year: ");
        yearL.setBounds(266, 11, 37, 14);
        contentPane.add(yearL);

        yearField = new JTextField();
        yearField.setBounds(301, 8, 86, 20);
        contentPane.add(yearField);
        yearField.setColumns(10);



        JLabel dayOfW;
        dayOfW = new JLabel("The day of the week is");
        dayOfW.setBounds(10, 153, 126, 14);
        contentPane.add(dayOfW);

        JTextArea textArea = new JTextArea();
        textArea.setBounds(172, 148, 160, 19);
        contentPane.add(textArea);

        Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);
        int dayOfWeek = xmas.get(Calendar.DAY_OF_WEEK); // 6=Friday




    yearField.addActionListener(new ActionListener() 
    {

        @Override
        public void actionPerformed(ActionEvent e)
        {

        }
    });
}
}

Thank you very much

You have any number of options...

You Could

Use a FocusListener on each field and when focusLost is called, validate the state of each field to determine if you have enough information to perform the required calculations...but this doesn't take into account what might happen if the user simply presses Enter on the last field...

You Could

Use an ActionListener on each field to detect when the user presses Enter (or the individual fields are actioned) and validate the state of each field to determine if you have enough information to perform the required calculations, but this doesn't take into account the case where the user doesn't press Enter on the field

You Could

Do both, use a FocusListener and ActionListener which simply calls a method that validates the state of each field to determine if you have enough information to perform the required calculations

You Could

Have a JButton that the user is required to press in order to perform the calculations. When activated it would validate the state of each field to determine if you have enough information to perform the required calculations

Take a look at:

You could even use an InputVerifier , see Validating Input for more details

Now, having said all that, you're main problem is a reference issue.

All you fields are declared locally to the constructor. While you could declare them as final and you'd be able to access them from within the inner class of the ActionListener , personally, I would declare them as instance variables, so that you could access them from anywhere within the class itself. This provides you with a greater opportunity to implement the logic as you need.

Dont use awt listener on swing component. swing comes out with DocumentListener which will listen for field text change.

yearField.getDocument().addDocumentListener(new DocumentListener() {
public void changedUpdate(DocumentEvent e) {
  calc();
}
public void removeUpdate(DocumentEvent e) {
  calc();
}
public void insertUpdate(DocumentEvent e) {
  calc();
}

public void calc() {
   //get values from fields
   //pass them to gregorian calendar constructor
   //get day of week from calendar
   //print day to label
}
});

Try this:

yearField.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent arg0) {

        //check the value of the other input fields
        //do the calculations

        textArea.setText("the result here");    
    }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM