Input Validator : FocusLost event handling

I am new to working with FocusListener and I am trying to use it validate the input of a textfield to be an integer.

This seems like a seemingly simple thing to do, but I am getting errors.

Here is a portion of the code where I make the textfield and assign it to a focus listener.

InputValidator i =new InputValidator();

...

resolutionlabel =new JLabel("Resolution: ");

p.add(resolutionlabel);

resolutiontextbox =new JTextField("3200");

resolutionlabel.setLabelFor(resolutiontextbox);

resolutiontextbox.addFocusListener(i);

p.add(resolutiontextbox);

Here is the important parts of the focus listener code:

publicclass InputValidatorextends FocusAdapter

{

public InputValidator()

{

}

publicvoid focusLost(FocusEvent event)

{

validate((TextField)(event.getSource()));

}

...

privatevoid validate(TextField field)

{

...

}

}

The error I am getting is on the line where I call the validate function and is listed as :

java.lang.ClassCastException: javax.swing.JTextField

[1776 byte] By [aei_tottena] at [2007-10-2 12:19:58]
# 1

this might be an alternative way - it won't accept non-digit characters

import javax.swing.*;

import java.awt.*;

import javax.swing.text.*;

class Testing extends JFrame

{

public Testing()

{

setLocation(400,300);

setDefaultCloseOperation(EXIT_ON_CLOSE);

JPanel jp = new JPanel();

JTextField tf = new JTextField(new NumberLimiter(),"3200",10);

jp.add(tf);

getContentPane().add(jp);

pack();

}

class NumberLimiter extends PlainDocument

{

public void insertString(int offs, String str, AttributeSet a) throws BadLocationException

{

char[] characters = str.toCharArray();

for(int x = 0, y = characters.length; x < y; x++)

{

if(Character.isDigit(characters[x]) == false)

{

java.awt.Toolkit.getDefaultToolkit().beep();

return;

}

}

super.insertString(offs, str, a);

}

}

public static void main(String[] args){new Testing().setVisible(true);}

}

Michael_Dunna at 2007-7-13 9:08:46 > top of Java-index,Security,Event Handling...
# 2
Thanks, I will try something like that. I am still interested in finding out what is wrong with my code though. Learn through mistakes.~Brandy
aei_tottena at 2007-7-13 9:08:46 > top of Java-index,Security,Event Handling...
# 3
Figured out the problem (well someone else saw it) it was the difference between using JTextField and TextField.Brandy
aei_tottena at 2007-7-13 9:08:46 > top of Java-index,Security,Event Handling...