import java.awt.Button;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
public class MyWindowDemo {
private Frame f;
private Button btn;
private TextField textField;
private TextArea textArea;
private Dialog dialog;
private Label label;
private Button okButton;
public MyWindowDemo() {
init();
}
private void init() {
f = new Frame("my window");
f.setBounds(300, 100, 600, 500);
f.setLayout(new FlowLayout());
textField = new TextField(60);
btn = new Button("转到");
textArea = new TextArea(25, 70);
dialog = new Dialog(f, "提示信息-self", true);
dialog.setBounds(400, 300, 200, 150);
dialog.setLayout(new FlowLayout());
label = new Label();
okButton = new Button("确定");
dialog.add(label);
dialog.add(okButton);
f.add(textField);
f.add(btn);
f.add(textArea);
myEvent();
f.setVisible(true);
}
private void myEvent() {
textField.addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_ENTER) {
showDir();
}
}
});
okButton.addActionListener(e -> dialog.setVisible(false));
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
dialog.setVisible(false);
}
});
btn.addActionListener(e -> showDir());
f.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private void showDir() {
String dirPath = textField.getText();
File file = new File(dirPath);
if (file.exists() && file.isDirectory()) {
textArea.setText("");
String[] list = file.list();
for (String name : list) {
textArea.append(name + "\r\n");
}
} else {
String errorInfo = dirPath + "目录不存在,请重新输入!";
label.setText(errorInfo);
dialog.setVisible(true);
}
textField.setText("");
}
public static void main(String[] args) {
new MyWindowDemo();
}
}
网友评论