Reputation: 100
Compilation and Execution is successful in this program . But When i type some characters the frame isn't showing those character within it. why ? what is the error.?
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
class frameadapter extends WindowAdapter
{
newframe newthis;
public frameadapter(newframe n)
{
newthis=n;
}
public void windowClosing(WindowEvent we)
{
newthis.setVisible(false);
System.exit(0);
}
}
class keyadapter extends KeyAdapter
{
newframe keythis;
public keyadapter(newframe n1)
{
keythis=n1;
}
public void KeyTyped(KeyEvent ke)
{
keythis.keymsg+=ke.getKeyChar();
System.out.println(keythis.keymsg);
keythis.repaint();
}
}
public class newframe extends Frame implements MouseListener
{
int mouseX;
int mouseY;
String keymsg="This is a Test";
String msg="";
public newframe()
{
addKeyListener(new keyadapter(this));
addWindowListener(new frameadapter(this));
addMouseListener(this);
this.setSize(600,600);
this.setVisible(true);
}
public void paint(Graphics g)
{
g.drawString(keymsg,100,100);
g.drawString(msg, 500, 200);
}
public void mouseClicked(MouseEvent e) {
mouseX=this.getX();
mouseY=this.getY();
msg="MOUSE CLICKED AT";
repaint();
}
public void mousePressed(MouseEvent e) {
mouseX=this.getX();
mouseY=this.getY();
msg="MOUSE PRESSED AT";
repaint();
}
public void mouseReleased(MouseEvent e) {
mouseX=this.getX();
mouseY=this.getY();
msg="MOUSE RELEASED AT";
this.setForeground(Color.WHITE);
this.setBackground(Color.BLACK);
repaint();
}
public void mouseEntered(MouseEvent e) {
mouseX=this.getX();
mouseY=this.getY();
msg="MOUSE ENTERED AT";
repaint();
}
public void mouseExited(MouseEvent e) {
mouseX=this.getX();
mouseY=this.getY();
msg="MOUSE EXITED AT";
repaint();
}
public static void main(String args[])
{
newframe n=new newframe();
}
}
The Error i think is in the Keyadapter class.But Unable to find a solution.
Upvotes: 0
Views: 36
Reputation: 347194
KeyListener
only responds to key events when the component it is registered to is focusable AND has keyboard focusFrame
is not focusable, from a key event standpoint, this makes it impossible for it to, but default, receive key event notification...Unless you have some desperate need to do so, I would recommend against using Frame
and instead, use a JFrame
as your window, as AWT is 15+ years out of date and generally is not longer used. Take a look at Creating a GUI With JFC/Swing for more details
Instead, start with a JPanel
, override it's paintComponent
method be perform your custom painting there. Take a look at Performing Custom Painting for more details.
Use the key bindings API to regsiter key actions against the panel. This will allow you to define the focus level required for the panel to receive key event notification
Upvotes: 2