Help me to understand, pls.

C

chirs

Hi,

Here is the applet, which displays a red x. It should display a
letter and a number when I type a key. The problem is line //a and
//b. Why do they cause problem? Why does it show a red x?

If I do not use these two lines and use a line

this.requestFocus();

it does not work either. But why? Since line //c is ok. What's wrong
with "this."? Line //c does not cause any problem. But I still need
to click the applet to get the focus. It seems there is no way to set
focus thru code on the applet.


Below is the code. Thanks a lot - Chris

import java.applet.*;
import java.awt.*;


public class Echo extends Applet {
int m;
Echo st=new Echo();//a
public void init() {

//requestFocus();//c
st.requestFocus();//b
setBackground(Color.pink);
}

public void paint(Graphics g) {
if (!(m==0)){
g.drawString(Integer.toString(m),100,100);
g.drawString("" + (char)m,200,200);
g.drawString("test" + 1,200,300);}
}

public boolean keyDown(Event evt, int key) {
m=key;
repaint();
return true;
}
}
 
A

Andrew Thompson

import java.applet.*;
import java.awt.*;

to detect an event you will most
likely need to..

import java.awt.event.*;
public class Echo extends Applet {
int m;
Echo st=new Echo();//a

You do not need to instantiate
applets like this, the applet
tag causes the init() method
to be called.

public void init() {

//requestFocus();//c
st.requestFocus();//b
setBackground(Color.pink);
}

public void paint(Graphics g) {
if (!(m==0)){
g.drawString(Integer.toString(m),100,100);
g.drawString("" + (char)m,200,200);
g.drawString("test" + 1,200,300);}
}

public boolean keyDown(Event evt, int key) {

keydown is deprecated, but since you
did not have it attached to anything,
it makes little difference.
m=key;
repaint();
return true;
}
}

You might get some benefit from
looking at a working example that
detects keyevents, have a look at..
<http://www.physci.org/launcher.jsp#StringTokenizerFrame>

that links to source and a button to
launch it. The KeyEvent is actioned
at line 83.

Perhaps you should be consulting the
basic tutorials and JavaDocs a bit more,
and for the moment posting over at
comp.lang.java.help
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top