Note that there are some explanatory texts on larger screens.

plurals
  1. POCreate generic class for java program
    text
    copied!<p>I have written a class in Java for JTextField Focus Listener and I don't know how to write this class as generic class. Once I wrote the generic class it should be used by all the JTextFields how can I do this please tell me the way through coding. How to write a generic class for this following code:</p> <pre><code>package javaapplication7; import java.awt.FlowLayout; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import javax.swing.JFrame; import javax.swing.JTextField; import javax.swing.text.JTextComponent; public class testfocuss{ public static void main(String[] argv) throws Exception { JTextField component = new JTextField(20); JTextField component1 = new JTextField(20); JTextField component2 = new JTextField(20); JTextField component3 = new JTextField(20); component.addFocusListener(new MyFocusListener()); component1.addFocusListener(new MyFocusListener()); component2.addFocusListener(new MyFocusListener()); component3.addFocusListener(new MyFocusListener()); JFrame f = new JFrame(); f.layout(new FlowLayout()); f.add(component1); f.add(component); f.add(component2); f.add(component3); f.pack(); f.setVisible(true); } } class MyFocusListener extends FocusAdapter { //boolean showingDialog = false; public void focusGained(FocusEvent evt) { final JTextComponent c = (JTextComponent) evt.getSource(); String s = c.getText(); c.requestFocus(); c.selectAll(); for (int i = 0; i &lt; s.length(); i++) { if (!Character.isDigit(s.charAt(i))) { c.setSelectionStart(i); c.setSelectionEnd(i); break; } } } public void focusLost(FocusEvent evt) { final JTextComponent c = (JTextComponent) evt.getSource(); String s = c.getText(); if (evt.isTemporary()) { return; } for (int i = 0; i &lt; s.length(); i++) { if (!Character.isDigit(s.charAt(i))) { //System.out.println("must only contain digits"); c.requestFocus(); c.selectAll(); break; } } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload