- Java code
import java.awt.*;import java.awt.event.*;import java.io.*;class GuiDemo6{ public static void main(String []args) { MyGuiFrame mgf = new MyGuiFrame("文件目录"); }}class MyGuiFrame extends Frame{ private TextField tf; private TextArea ta; private Button btn; private Label lab; public MyGuiFrame(String title) { super(title); setBounds(200,150,500,600); setLayout(new FlowLayout()); tf = new TextField(50); btn = new Button("转到"); ta = new TextArea(30,65); add(tf); add(btn); add(ta); setVisible(true); myEvent(); } private void myEvent() { addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { setVisible(false); dispose(); System.exit(0); } }); tf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ta.setText(""); getFile(); } }); } private void getFile() { String str = tf.getText(); File file = new File(str); if(file.isDirectory()) { String [] names = file.list(); for(String name :names) { ta.append(name+"\r\n"); } } else { MyDialog dia = new MyDialog(this,"系统提示",true); dia.setStr(str); dia.run(); } }}class MyDialog extends Dialog{ private Label lab ; private Button btn; private String str; public MyDialog(Frame f, String s,boolean m) { super(f,s,m); setBounds(250,200,280,200); lab = new Label(); btn = new Button("确定"); setLayout(new FlowLayout()); add(lab); add(btn); } public void setStr(String str) { this.str = str; } public void run() { String info = "对不起!你指定的目录:"+str+"是出错误的!"; lab.setText(info); setVisible(true); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { setVisible(false); dispose(); } }); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { setVisible(false); dispose(); } }); }}
------解决方案--------------------------------------------------------
必须先添加事件,再setVisible(true),
严格地说来是,当添加了事件后,必须重新显示setVisible(true),事件才会生效,
如果本来就是可见的,再调用setVisible(true),事件也不会生效
详细可以研究:Component.show()的代码