PreventingButtonListener.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PreventingButtonListener extends JFrame implements ActionListener{
JTextField fld = new JTextField(5) ;
PreventingButtonListener(){
super("PreventingButtonListener") ;
setSize(300, 250) ;
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE) ;
setResizable(false) ;
fld.addFocusListener(
new FocusListener(){
public void focusGained(FocusEvent event) {}
public void focusLost(FocusEvent event) {
int i = (int) (Math.random() * 3) ;
switch(i){
case 0 :
System.out.println("random value : " + i);
fld.requestFocus() ;
break ;
case 1 :
System.out.println("random value : " + i);
i = (int) (Math.random() * 2) ;
if(i == 0){
System.out.println("JOptionPane not displayed, followed with button action.");
}else{
System.out.println("JOptionPane displayed, but button action not performed.");
JOptionPane.showMessageDialog(null, "Hello") ;
}
break ;
default :
System.out.println("random value : " + i);
System.out.println("Nothing to be done...");
break ;
}
}
}) ;
add(fld, "North") ;
JButton btn = new JButton("Hit me Repeatedly considering Note 1") ;
btn.addFocusListener(new FocusListener(){
public void focusGained(FocusEvent arg0) {
System.out.println("focus gained on button.");
}
public void focusLost(FocusEvent arg0) {
System.out.println("focus removed on button.");
}
}) ;
btn.addActionListener(this) ;
add(btn, "South") ;
String str = "Note 1 : Whenever, u click on button, and if the focus" + "\n" +
"after clicking is not in the textfield, then, plz" + "\n" +
"explicitly click in the JTextField." + "\n\n" +
"Note 2 : Kindly notice the output on cmd " + "\n" +
"and related focuses of GUI." + "\n\n" ;
JTextArea area = new JTextArea(str) ;
area.setEditable(false) ;
area.setWrapStyleWord(true) ;
area.setBackground(Color.LIGHT_GRAY) ;
add(new JScrollPane(area)) ;
setVisible(true) ;
}
public void actionPerformed(ActionEvent arg0) {
System.out.println("data of txtfld : >" + fld.getText() + "<");
}
public static void main(String[] args) {
new PreventingButtonListener() ;
}
}
the problem lies in the execution of the attached program???