Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: MouseListener

  1. #1
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Problem with validation

    I can't seem to find a solution for figuring out how to make the application not update the labels/text fields and sending data to the console window in the background. I have the If statements set up but not sure where I should send focus to if the number is invalid and make the program not continue. Any help would be appreciated, or ideas.
    else if (source == enterScoreButton)	{
                // parse the score
                int score = Integer.parseInt(scoreTextField.getText());
                // Validate the number is in proper range
                if (score < 0)
                	JOptionPane.showMessageDialog(null, "The lowest possible score for data entry is 0-Points. Please re-enter.", "Invalid Entry", JOptionPane.ERROR_MESSAGE);
     
    			else if (score > 100)
    				JOptionPane.showMessageDialog(null, "The highest possible score for data entry is 100-Points. Please re-enter.", "Invalid Entry", JOptionPane.ERROR_MESSAGE);
     
    			else
    			// calculate the results
                total += score;
                count++;
                average = total / count;
                if (score > best)
                	best = score;
     
                if (score < lowest)
                	lowest = score;
     
    			NumberFormat df = NumberFormat.getNumberInstance();
                NumberFormat nf = NumberFormat.getNumberInstance();
                df = new DecimalFormat("###.00");
                countTextField.setText(nf.format(count));
                averageTextField.setText(df.format(average));
                bestTextField.setText(nf.format(best));
                lowestTextField.setText(nf.format(lowest));
                System.out.println("  " + nf.format(count) + ". " + score);
    Last edited by _lithium_; January 17th, 2011 at 08:02 PM.


  2. #2
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 287 Times in 225 Posts
    Blog Entries
    4

    Default Re: MouseListener

    Can you please post something I can compile?
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

    Looking for a Java job? Visit - Java Programming Careers

  3. #3
    Member
    Join Date
    Dec 2010
    Posts
    69
    My Mood
    Busy
    Thanks
    4
    Thanked 0 Times in 0 Posts

    Default Re: MouseListener

    Yeah, here ya go, and thank you.

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.*;
    import java.lang.Math;
     
    public class StudentScoresApp	{
        public static void main(String[] args)	    {
     
    		System.out.println("  List of Student Scores Entered");
            JFrame frame = new StudentScoresFrame();
            frame.setVisible(true);
        }
     
    }
    class StudentScoresFrame extends JFrame		{
        public StudentScoresFrame()		{
            setTitle("Test Scores");
            setSize(310, 220);
            centerWindow(this);
            setResizable(false);
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            JPanel panel = new StudentScoresPanel();
            this.add(panel);
     
        }
    private void centerWindow(Window w) {
    	Toolkit tk = Toolkit.getDefaultToolkit();
    	Dimension d = tk.getScreenSize();
    	setLocation((d.width-w.getWidth())/2, (d.height-w.getHeight())/2);
    	}
    }
     class StudentScoresPanel extends JPanel implements ActionListener	{
        private JTextField  scoreTextField,
                            countTextField,
                            averageTextField,
                            bestTextField,
                            lowestTextField;
        private JLabel      scoreLabel,
                            countLabel,
                            averageLabel,
                            bestLabel,
                            lowestLabel;
        private JButton     enterScoreButton,
        					clearButton,
                            exitButton;
     
    	private int count = 0;
     
    	private double total = 0;
     
    	// total is a double to prevent truncation when
    	// calculating the average
    	private double average = 0;
    	private int best = 0;
    	private int lowest = 100;
     
        public StudentScoresPanel()	   {
            // display panel
            JPanel displayPanel = new JPanel();
            displayPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
     
     
            // score label
            scoreLabel = new JLabel("Test Score:");
            displayPanel.add(scoreLabel);
     
            // score text field
            scoreTextField = new JTextField(13);
            displayPanel.add(scoreTextField);
    		scoreTextField.addMouseListener(new AutoSelect());
     
     
     
            // count label
            countLabel = new JLabel("Number of Scores:");
            displayPanel.add(countLabel);
     
            // count text field
            countTextField = new JTextField(10);
            countTextField.setEditable(false);
            countTextField.setFocusable(false);
            displayPanel.add(countTextField);
     
            // average label
            averageLabel = new JLabel("Average Score:");
            displayPanel.add(averageLabel);
     
            // average text field
            averageTextField = new JTextField(13);
            averageTextField.setEditable(false);
            averageTextField.setFocusable(false);
            displayPanel.add(averageTextField);
     
            // best label
            bestLabel = new JLabel("Highest score:");
            displayPanel.add(bestLabel);
     
            // best text field
            bestTextField = new JTextField(12);
            bestTextField.setEditable(false);
            bestTextField.setFocusable(false);
            displayPanel.add(bestTextField);
     
            // lowest label
            lowestLabel = new JLabel("Lowest score:");
            displayPanel.add(lowestLabel);
     
            // lowest text field
            lowestTextField = new JTextField(10);
            lowestTextField.setEditable(false);
            lowestTextField.setFocusable(false);
            displayPanel.add(lowestTextField);
     
            // button panel
            JPanel buttonPanel = new JPanel();
            buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
     
            // enter score button
            enterScoreButton = new JButton("Enter Score");
            enterScoreButton.addActionListener(this);
            buttonPanel.add(enterScoreButton);
     
            // clear button
            clearButton = new JButton("End/Clear Entries");
            clearButton.addActionListener(this);
            buttonPanel.add(clearButton);
     
            // exit button
            exitButton = new JButton("Exit");
            exitButton.addActionListener(this);
            buttonPanel.add(exitButton);
     
            // add panels to main panel
            this.setLayout(new BorderLayout());
            this.add(displayPanel, BorderLayout.CENTER);
            this.add(buttonPanel, BorderLayout.SOUTH);
        }
     
        public void actionPerformed(ActionEvent e)	{
            Object source = e.getSource();
     
            if (source == exitButton){
            	if (count == 0){
    				lowest = 0;}
     
    			NumberFormat ef = NumberFormat.getNumberInstance();
                ef = new DecimalFormat("###.00");
    			System.out.println("\n  Highest: " + best + "  Lowest: " + lowest + "  Average: " + ef.format(average) + "\n");
     
    				System.out.printf("  Program terminated by the User.");
    				System.out.printf("\n");
    				System.exit(0);
     
                System.exit(0);
    		}
          else if (source == enterScoreButton)	{
                // parse the score
                int score = Integer.parseInt(scoreTextField.getText());
                // Validate the number is in proper range
                if (score < 0)
                	JOptionPane.showMessageDialog(null, "The lowest possible score for data entry is 0-Points. Please re-enter.", "Invalid Entry", JOptionPane.ERROR_MESSAGE);
     
    			else if (score > 100)
    				JOptionPane.showMessageDialog(null, "The highest possible score for data entry is 100-Points. Please re-enter.", "Invalid Entry", JOptionPane.ERROR_MESSAGE);
     
    			else
    			// calculate the results
                total += score;
                count++;
                average = total / count;
                if (score > best)
                	best = score;
     
                if (score < lowest)
                	lowest = score;
     
    			NumberFormat df = NumberFormat.getNumberInstance();
                NumberFormat nf = NumberFormat.getNumberInstance();
                df = new DecimalFormat("###.00");
                countTextField.setText(nf.format(count));
                averageTextField.setText(df.format(average));
                bestTextField.setText(nf.format(best));
                lowestTextField.setText(nf.format(lowest));
                System.out.println("  " + nf.format(count) + ". " + score);
     
            }
            else if (source == clearButton)		{
    			if (count == 0)
    				lowest = 0;
    			NumberFormat df = NumberFormat.getNumberInstance();
                df = new DecimalFormat("###.00");
    			System.out.println("\n  Highest: " + best + "  Lowest: " + lowest + "  Average: " + df.format(average) + "\n");
    			System.out.println("  Scores were cleared...\n  Next Set:");
    			count = 0;
    			total = 0;
    			average = 0;
    			best = 0;
    			lowest = 0;
     
                scoreTextField.setText("");
    			countTextField.setText("");
                averageTextField.setText("");
                bestTextField.setText("");
                lowestTextField.setText("");
    		}
     
        }
     
    }
     class AutoSelect extends MouseAdapter {
    	public void mouseClicked(MouseEvent e)
    			{
    				if (e.getComponent() instanceof JTextField)
    				{
    					JTextField t = (JTextField) e.getComponent();
    					t.selectAll();
    				}
    			}
     
    	}

Similar Threads

  1. [SOLVED] implements MouseListener doesn't work why
    By voltaire in forum AWT / Java Swing
    Replies: 2
    Last Post: May 1st, 2010, 04:30 PM
  2. MouseListener & MouseMotionListener
    By JavaLearner in forum AWT / Java Swing
    Replies: 9
    Last Post: March 26th, 2010, 07:18 AM