Solved

How do I make a pop up in Swing GUI if wrong data is entered in a text field.

Posted on 2009-04-06
5
331 Views
Last Modified: 2013-12-14
I try to make the input field accept only numbers preceded by a mathematical operator (+ - * /). for example: +7. if I enter just 7, it should pop up a window saying the same. I am using netbeans. Here is the Keypressed event code for you.
Please help me.
private void txtNumberKeyPressed(java.awt.event.KeyEvent evt) {                                     

        // KeyPressed handling code here:

        String badChar = "`!@#$[]\";%^&)~(_][{}|';:?|><,";

        char c = evt.getKeyChar();

        int keyCode = evt.getKeyCode();

        if(badChar.indexOf(c)>=0 || c <'0' && c>'9' || c >='a' && c <='z'

                || c >= 'A' && c <= 'Z' && keyCode != KeyEvent.VK_BACK_SPACE &&

                keyCode != KeyEvent.VK_ENTER)

        {

            evt.consume();

        }

        if(keyCode ==KeyEvent.VK_ENTER)

        {

            dataDisplay.append(txtNumber.getText()+ '\n');

            //now clear the textbox ready for next entry

            txtNumber.setText(null);

        }

    }

Open in new window

0
Comment
Question by:chandanchoubey
  • 2
  • 2
5 Comments
 
LVL 12

Assisted Solution

by:basav_com
basav_com earned 50 total points
Comment Utility
0
 

Author Comment

by:chandanchoubey
Comment Utility
Thanks for help basav_com. I tried using JOptionPane. It is giving me pop up. thats good. but it pops up even if I enter digits. I want pop should only appear when I enter text or not digits. please take a look of my code. What am I doing wrong?
Thanks for your help.
    private void txtNumberKeyPressed(java.awt.event.KeyEvent evt) {                                     

        // KeyPressed handling code here:

        String badChar = "`!@#$[]\";%^&)~(_][{}|';:?|><,";

        char c = evt.getKeyChar();

        int keyCode = evt.getKeyCode();

        if(badChar.indexOf(c)>=0 || c <'0' && c>'9' || c >='a' && c <='z'

                || c >= 'A' && c <= 'Z' && keyCode != KeyEvent.VK_BACK_SPACE &&

                keyCode != KeyEvent.VK_ENTER)

        {

            evt.consume();

        }
 

String goodChar = "1234567890+-/*";

        char d = evt.getKeyChar();

        if(keyCode ==KeyEvent.VK_ENTER)

            if(goodChar.indexOf(d) >=0 && goodChar.indexOf(d) <=14)

        {

                dataDisplay.append(txtNumber.getText()+ '\n');
 

            }

            else

            {

            JOptionPane.showMessageDialog(null, "wrong key");

            }

           

            //now clear the textbox ready for next entry

            txtNumber.setText(null);

Open in new window

0
 
LVL 17

Accepted Solution

by:
Thomas4019 earned 200 total points
Comment Utility
This code should not be put in a keyPressed. You should have a JButton with an action listener. Then call get Text to get the whole string they input. Here is a simple example.
import javax.swing.*;

import java.awt.*;

import java.awt.event.*;
 

class Example extends JFrame implements ActionListener

{

	JTextField input;
 

	Example()

	{

		setSize(320,240);

		setDefaultCloseOperation(EXIT_ON_CLOSE);
 

		input = new JTextField();

		add(input,BorderLayout.CENTER);
 

		JButton submit = new JButton("Submit");

		submit.addActionListener(this);

		add(submit,BorderLayout.SOUTH);
 

		setVisible(true);

	}
 

	public void actionPerformed(ActionEvent evt)

	{

		if(!input.getText().matches("^[\\+\\-\\*\\/].*"))

		{

			JOptionPane.showMessageDialog(null,"Bad Input");

		}
 

		//CODE USING INPUT HERE

	}
 

	public static void main(String args[])

	{

		new Example();

	}

}

Open in new window

0
 

Author Comment

by:chandanchoubey
Comment Utility
Thanks Thomas4019. I really appreciate it. But I dont want a JButton. I want JOptionPane to appear when user presses "enter key" rather than clicking on Submit button
0
 
LVL 17

Assisted Solution

by:Thomas4019
Thomas4019 earned 200 total points
Comment Utility
very simple, simply add the actionlistener on the JTextField and remove the JButton, here is the new source code.
import javax.swing.*;

import java.awt.*;

import java.awt.event.*;
 

class Example extends JFrame implements ActionListener

{

	JTextField input;
 

	Example()

	{

		setSize(320,240);

		setDefaultCloseOperation(EXIT_ON_CLOSE);
 

		input = new JTextField();

		input.addActionListener(this);

		add(input,BorderLayout.CENTER);
 

		setVisible(true);

	}
 

	public void actionPerformed(ActionEvent evt)

	{

		if(!input.getText().matches("^[\\+\\-\\*\\/].*"))

		{

			JOptionPane.showMessageDialog(null,"Bad Input");

		}
 

		//CODE USING INPUT HERE

	}
 

	public static void main(String args[])

	{

		new Example();

	}

}

Open in new window

0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
word0 challenge 3 56
wordmultiple challenge 12 89
JDeveloper 12c for 32 bit 4 34
how do i compare an object based on two fields 6 28
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
The viewer will learn how to use NetBeans IDE 8.0 for Windows to connect to a MySQL database. Open Services Panel: Create a new connection using New Connection Wizard: Create a test database called eetutorial: Create a new test tabel called ee…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now