954,554 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

For the Swing gurus

yes, there's an area of Java I'm almost a complete novice in (so far, I'm going full steam ahead :cheesy: ).

I've the following code to filter out non-numeric input from a JTextField (which is meant to contain a timeout interval in minutes, that's why).

private void dumpNonNumericInput(KeyEvent e) {
        char input = e.getKeyChar();
        String oldText = ((JTextField)e.getSource()).getText();
        if (input != KeyEvent.VK_BACK_SPACE && input != KeyEvent.VK_DELETE &&
            (input < '0' || input > '9')) {
            JOptionPane.showMessageDialog(this, "Numeric input required",
                                          "Input error",
                                          JOptionPane.ERROR_MESSAGE);
            e.consume();
            ((JTextField)e.getSource()).setText(oldText);

        }
    }


This method works like a charm, that's not the problem.
The problem is that is I remove the error message popup (just the showMessageDialog command) the method no longer removes the faulty input either.
I THINK it's something to do with Swing thread timing, but I'm not sure.
Neither do I know how to cure this, which is more important at the moment as I'd rather not have that popup appear every time someone makes a typo.

I could probably subclass JTextField but that may be more trouble than it's worth.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

Can you do it with a try catch statement?

ProFreelance
Newbie Poster
17 posts since Aug 2005
Reputation Points: 10
Solved Threads: 0
 

A better alternative would be to disable text input altogether (call setEditable(false) on the text field. This deals with the problem of people putting in garbage input. Then all you need to do is use regular expression on the character that was input. Then use reg exp for input
if(stringvar.matches("\\d")){}

Not sure why removing a showMessageDialog would have any effect on the following code.

Gink
Light Poster
46 posts since Feb 2005
Reputation Points: 10
Solved Threads: 0
 

hi jwenting,

I have attached a Textfield which takes number of columns(maximum number of characters that the textfield can take) as parameter. If you use the usual textfields with keylistener, you can set illegal characters programattically. This textfield(one attached) does not allow illegal characters either by entry or progammatically. You can run the program attached and check out and tell me whether it was useful.

TextFieldDemo is the one with main method.

I am not sure whether this is exactly your requirement

regards
Srinivas

Attachments NumericTextField.java (1.68KB) TextFieldDemo.java (0.27KB)
cheenu78
Light Poster
45 posts since Jun 2005
Reputation Points: 10
Solved Threads: 0
 

Cheers, I'll give it a look.

Gink, the idea is to allow only certain input. If it were readonly I'd have used a label or something else instead :)

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

Im not suggesting to make it read-only. What im saying is add a keylistener and whenever the user presses a key just update the textfield accordingly. The only reason I said uneditable is to prevent people from typing in characters that the keylistener doesnt respond to. It is still editable by the program, and the user wont know it's uneditable.

Gink
Light Poster
46 posts since Feb 2005
Reputation Points: 10
Solved Threads: 0
 

ah.

Found I can't catch shortcut keys (like Alt-T, Alt-X, etc.) using this system so I abandoned it.
Instead I now validate the field when it's value is read out instead of when it's input and give an error then.

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

Why not a boolean check method?

public boolean check(String text)
{
   try
   {
        Double.parseDouble(text);
        return true;
   }
   catch
   {
       JOptionPane.showMessageDialog(null,"Numeric crap only");
       return false;
   }
   return false;
}
server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

yes, something like that :)
Thought to be a tad more friendly with my users though :p

try {
            Integer.parseInt(timeout.getText());
        } catch (NumberFormatException ex) {
            JOptionPane.showMessageDialog(this,
                                          "Timeout interval must be a number",
                                          "Input error",
                                          JOptionPane.ERROR_MESSAGE);
            return;
        }
jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

What do you mean your users? Are you teaching a class or something? Will however see the code?

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Inp extends JFrame{
    
    JPanel panel;
    JTextField field;
    Container container;
    InpKeyHandler handler;

    public Inp(){
        panel = new JPanel();
        field = new JTextField();
        field.setBackground(Color.WHITE);
        field.setHorizontalAlignment(JTextField.RIGHT);
        
        handler = new InpKeyHandler();
        
        container = getContentPane();
        container.setLayout(new BorderLayout());        
        field.addKeyListener(handler);
        
        
        field.setText("");
        field.setEditable(false);
        container.add(field,BorderLayout.NORTH);
        setSize(500,500);
        setVisible(true);
        
    }
    
    
    public static void main(String args[]){
        Inp in = new Inp();
        in.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);        
    }
 
    public class InpKeyHandler extends KeyAdapter{
        String keyTyped;
        public void keyTyped(KeyEvent event){
          
          if((""+(event.getKeyChar())).matches("\\d")){
            keyTyped = field.getText();
            keyTyped += event.getKeyChar();
            field.setText(keyTyped);
          }
         }
            
    }
}
Gink
Light Poster
46 posts since Feb 2005
Reputation Points: 10
Solved Threads: 0
 

:lol: :lol: :lol: :lol:


I just realized what you mean't..hahaha I'm a bit slow at times.

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 
What do you mean your users? Are you teaching a class or something? Will however see the code?

I'm working on my SCJD exam. That means an examiner from Sun will see the code (and run it), and I hope some colleagues as friends as well if I can find people to test it first :)

And of course I work in the business, I doubt our customers would like such messages :eek:

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

I'll test it if you need me too. I'm good at trying to make things not work!

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

will keep it in mind.
Got the first draft of the network server done, now working on the client application, and then to glue them together :)

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 

Will this be harder than the scjp exam?

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

yes, that's the idea :)
SCJP consists of learning a lot of stuff by rote and answering 60something multiple choice questions (with a rather low passing score).
SCJD consists of creating a complete client/server application from scratch including the database server and all documentation without using anything that's not part of the JDK itself (so no 3rd party or even optional Sun libraries, and some standard libraries are also not allowed, for example JDBC is explicitly disallowed).

jwenting
duckman
Team Colleague
8,392 posts since Nov 2004
Reputation Points: 1,662
Solved Threads: 337
 
yes, that's the idea :) SCJP consists of learning a lot of stuff by rote and answering 60something multiple choice questions (with a rather low passing score). SCJD consists of creating a complete client/server application from scratch including the database server and all documentation without using anything that's not part of the JDK itself (so no 3rd party or even optional Sun libraries, and some standard libraries are also not allowed, for example JDBC is explicitly disallowed).


pffsshhhhh, easy. :lol: :lol:

Just joking, let me know how do on it.

server_crash
Postaholic
2,111 posts since Jun 2004
Reputation Points: 113
Solved Threads: 20
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You