/* Copyright (c) SEMM NL All rights reserved.
Author : Paul Hamaker. Part of JavaLessons.com
This code is for educational purposes only. Use at own risk.*/

1. import javax.swing.* ; 

2. import java.awt.* ; 

3. import java.awt.event.*; 

4.  

5. public class FocusSw 

6.     extends JApplet 

7.     implements ActionListener 

8.

9.   JButton  btn ; 

10.   JTextField tf1, tf2 ; 

11.   JLabel lbl ; 

12.   Container cp ; 

13.  

14.   public void 

15.   actionPerformed( ActionEvent ev ) 

16.   { 

17.     String str ; 

18.     str = tf1.getText(); 

19.  

20.     if ( ! str.startsWith ("a") ) 

21.     { 

22.       lbl.setText ( "Has to begin with a" ) ; 

23.       tf1.requestFocus(); 

24.       tf1.setCaretPosition (0); 

25.       return

26.     } 

27.     str = tf2.getText(); 

28.     if ( ! str.startsWith ("b") ) 

29.     { 

30.       lbl.setText ( "Has to begin with b" ) ; 

31.       tf2.requestFocus(); 

32.       tf2.setCaretPosition (0); 

33.       return

34.     } 

35.     lbl.setText ( "Carry on, men" ) ; 

36.   } 

37.  

38.   public 

39.   FocusSw( ) 

40.   { 

41.     btn = new JButton ( "Check 'm" ) ; 

42.     tf1 = new JTextField ( 10 ); 

43.     tf2 = new JTextField ( 10 ); 

44.     lbl = new JLabel ( "Fill out, please" ) ; 

45.   } 

46.  

47.   public void 

48.   init() 

49.   { 

50.     cp = getContentPane( ); 

51.     cp.setLayout( new FlowLayout() ); 

52.  

53.     cp.add ( btn) ; 

54.     cp.add ( tf1 ) ; 

55.     cp.add ( tf2 ) ; 

56.     cp.add ( lbl ) ; 

57.     cp.setBackground ( Color.orange ) ; 

58.  

59.     btn.addActionListener ( this ) ; 

60.     tf1.requestFocus(); 

61.   } 

62.