Promblem in KeyListener on JFrame
Hi,
I have created a JFrame implementing the keylistener and containing a JToolBar, JDesktopPane and few JInternalFrame; but the problem is that whenever I run the application first time, the keylistener working fine but as I focus other components such as JInternalFrame; my implemented KeyListener never runs again, I think that there is a problem of focus but still I am unable to figure out and fix the bug. Here I am enclosing the code, kindly try it and let me where I am mistaking.
import javax.swing.*;
import javax.swing.JButton;
import java.awt.event.*;
import javax.swing.event.*;
import java.awt.event.AWTEventListener;
import java.awt.event.KeyEvent;
import java.awt.AWTEvent;
import java.awt.Toolkit;
import java.awt.*;
public class workAround {
public static void main(String args[]) {
workAroundUI ui = new workAroundUI();
ui.setSize(300, 300); ui.show();
}
}
class workAroundUI extends JFrame implements AWTEventListener
{ JButton b;
public JInternalFrame ifrm =null;
public JInternalFrame getJInternalFrame()
{
if(ifrm==null)
{
ifrm = new JInternalFrame();
ifrm.setClosable(true);
ifrm.setDefaultCloseOperation(JInternalFrame.HIDE_ ON_CLOSE);
ifrm.setBounds(0,0,200,200);
ifrm.addInternalFrameListener(new InternalFrameAdapter(){
public void internalClosed(InternalFrameEvent e){
}
});
}//end
return ifrm;
}//end
public JDesktopPane jDesktopPane = null;
public JDesktopPane getJDesktopPane()
{
if(jDesktopPane==null)
{
jDesktopPane = new JDesktopPane();
jDesktopPane.add(getJInternalFrame());
}
return jDesktopPane;
}
public JToolBar tool = null;
public JToolBar getTool()
{
if(tool==null)
{
tool = new JToolBar();
tool.add(b);
}
return tool;
}
workAroundUI() {
b = new JButton("CLICK ME");
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try{
getJInternalFrame().show();
getJInternalFrame().setSelected(true);
getJDesktopPane().updateUI();
}catch(Exception e1){}
}
});
getContentPane().add(getTool(),BorderLayout.NORTH) ;
getContentPane().add(getJDesktopPane(),BorderLayou t.CENTER);
Toolkit.getDefaultToolkit().addAWTEventListener(th is, KeyEvent.KEY_EVENT_MASK);
}
public void eventDispatched(AWTEvent e) {
KeyEvent key = (KeyEvent)e;
if((e.getID()==KeyEvent.KEY_PRESSED)&&(key.isContr olDown())&&(key.getKeyCode()==KeyEvent.VK_C))
{ try{
getJInternalFrame().show();
getJInternalFrame().setSelected(true);
getJDesktopPane().updateUI();
}catch(Exception e1){}}
}
}
How to use:
Step 1: Compile the java file âworkAround.javaâ and run it
Step 2: press ctrl+C to open the JInternalFrame
Step 3: close JInternalFrame by using mouse
Step 4: try step 2, u will notice the error that it is not working
Note: I am using JDK1.4 and secondly I observed that whenever user get the focus on other window application and then again gain the focus on java application it runs very well once, but its not a proper solution.
Looking forward to your early response
Regards,
M.A.Bamboat
|