黑马程序员-利用GUI 做一个像我的电脑一样的索引

来源:互联网 发布:excel数据可视化插件 编辑:程序博客网 时间:2024/04/28 03:25

------- android培训、java培训、期待与您交流! ----------

//需求:做一个像我的电脑一样的索引

package com.itheima;
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.ActionEvent;
import java.awt.event.ActionListener;
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 GUIReview {
 private Frame frame;
 private Button but;
 private TextField tf;
 private TextArea ta;
 private Dialog dia;
 private Label lab;
 private Button myBut;
 private File file;
 GUIReview(){
  init();
 }
 public void init(){
  //1.创建一个Frame窗体,并进行基本设置
  frame = new Frame();
  frame.setBounds(300,100,650,600);
  frame.setLayout(new FlowLayout());//Frame窗体默认的布局是BorderLayout
  
  //2.对窗体里的组件进行基本设置
  tf = new TextField(70);
  ta = new TextArea(30,80);
  but = new Button("转到");
  
  //3.对组件进行添加
  frame.add(tf);
  frame.add(but);
  frame.add(ta);
  
  //4.创建错误提示的对话框
  dia = new Dialog(frame,"提示信息",true);
  dia.setBounds(350,150,250,150);
  dia.setLayout(new FlowLayout());
  lab = new Label();//Label 是专门封装文字的组件
  myBut = new Button("确定");
  dia.add(lab);
  dia.add(myBut);
  
  //5.调用监听机制,对组件进行监听
  myEvent();
  
  frame.setVisible(true);
  
  
 }
 //各个组件添加监听器
 public void myEvent(){
  frame.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent e){
    System.exit(0);
   }
  });
  dia.addWindowListener(new WindowAdapter(){
   public void windowClosing(WindowEvent e){
    System.exit(0);
   }
  });
  myBut.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e){
    System.exit(0);
   }
  });
  //对but进行操作 目的:一按but 就刷新
  but.addActionListener(new ActionListener(){
   public void actionPerformed(ActionEvent e){
    showDir();
   }
  });
  //对搜索栏添加键盘机制   目的一按回车就刷新
  tf.addKeyListener(new KeyAdapter(){
   public void keyPressed(KeyEvent e){
    if(e.getKeyCode()==KeyEvent.VK_ENTER)
     showDir();
   }
  });
  
 }
 public void showDir(){
  ta.setText("");//对文本区域进行清空
  String dir = tf.getText();
  file = new File(dir);
  if(file.exists()){
   String[] dirNames = file.list();
   for(String dirName : dirNames){
    ta.append(dirName+"\r\n");//这样是在末尾添加
   }
  }else{
   String mes="您查找的目录"+file+"不存在,请重新输入";
   lab.setText(mes);
   dia.setVisible(true);
  }
 }
 public static void main(String[] args){
  new GUIReview();
 }
}
原创粉丝点击