import java.awt.*;
import java.awt.event.*;
import javax.swing.*;public class FocusFrame extends JFrame{
private Frame f;
private Button b1,b2;
private Container c;
private myFocusListener fl;
public static void main(String s[]){
FocusFrame mainframe= new FocusFrame();
mainframe.go();
}
public FocusFrame(){
b1=new Button("focus1");
b2=new Button("focus2");
setSize(300,100);
c=getContentPane();
c.add(b1,"North");
c.add(b2,"Center");
fl=new myFocusListener();
b1.addFocusListener(fl);
System.out.print("start");
}
void go(){
setVisible(true);
}
}
class myFocusListener implements FocusListener{
public void focusGained(FocusEvent evt){
showFocusMsg(evt);
}
public void focusLost(FocusEvent evt){
showFocusMsg(evt);
// System.exit(0);
}
public void showFocusMsg(FocusEvent evt){
if(evt.getID()==FocusEvent.FOCUS_GAINED){
System.out.print("gain focus");
}
else if(evt.getID()==FocusEvent.FOCUS_LAST){
System.out.print("lost focus");
}
if(evt.isTemporary()){
System.out.print("暂时event");
}
else{
System.out.print("永久event");
}
}
}
编译没有问题,只是:
1。为什么只有将
// System.exit(0);
一句的注释符去掉之后才能在按tab之后执行System.exit(0);后在输出窗口里看到:
“startgain focus永久eventlost focus永久event”
如果保持注释符号,怎样也看不到我预先设计的输出文字?
2。关于接口的一个疑问。
在这段代码中是否相当于通过接口将调用规范告知系统,使得系统能够调用此接口进而进入我自己的myFocusListener执行代码?这和win32中的回调函数是否相同原理?
多谢f_acme(沧海一声笑)前辈的指点,不过为什么用print就不行呢,println特殊在什么地方?
另外还有问题2期待回答。
把所有的System.out.print改为System.out.println,不过我也不知道为什么System.out.print就不行呢,我是在试了很久的时候发现运行的时候连“start”都不会打印出来,才发觉到的。
因为out是个输出流,我这里没有环境,不过我估计是因为print没有立即刷新输出流
而print在输出后不换行
而print在输出后不换行
地球都知道
关键是他后面的实质是什么分别
// System.exit(0);
把System.exit(0);放到下面行试一下行不!
public void print(String s) {
if (s == null) {
s = "null";
}
write(s);
}private void write(String s) {
try {
synchronized (this) {
ensureOpen();
textOut.write(s);
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush && (s.indexOf('\n') >= 0)) //这里了,用print还要换行回车它才刷新,而println的newLine()方法里面没有此要求,所以就。
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
private void newLine() {
try {
synchronized (this) {
ensureOpen();
textOut.newLine();
textOut.flushBuffer();
charOut.flushBuffer();
if (autoFlush) //刷新
out.flush();
}
}
catch (InterruptedIOException x) {
Thread.currentThread().interrupt();
}
catch (IOException x) {
trouble = true;
}
}
在System类中out是这样定义的:
public final static PrintStream out = nullPrintStream();
可是nullPrintStream()方法的代码却奇怪的很:
private static PrintStream nullPrintStream() throws NullPointerException {
if (currentTimeMillis() > 0)
return null;
throw new NullPointerException();
}
搞不明白了,谁解释一下,为什么out对象可以使用的?咋看都是null的呢?