对话框不能单独存在,依赖于窗体,有显示标题,有模式
获取Dialog对象,new出来,构造参数:Frame对象,String的标题,模式
窗体内部的内容,Label对象,Button对象,调用Dialog对象的add()方法,把这两个添加进去
Dialog也是一个普通的窗体,需要设置尺寸和位置
这个Dialog窗体不用加入到Frame窗体中,只需要设置是否显示就可以了
对话框的叉号,给对话框添加窗体事件
调用Dialog对象的addWindowListener()方法,设置,重写windowClosing()方法,方法里面调用Dialog对象setVisible(flase),隐藏掉
显示信息
调用Label对象的setText()方法,设置文本
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.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; public class FrameDemo { private Frame frame; private TextField tf; private TextArea ta; private Button button; private Dialog dialog; private Label label; public FrameDemo() { init(); } /** * 初始化 */ public void init() { frame = new Frame("测试窗体"); frame.setBounds(300, 200, 300, 400); frame.setLayout(new FlowLayout()); tf = new TextField(20); button = new Button("转到"); ta = new TextArea(30, 30); frame.add(button); frame.add(tf); frame.add(ta); dialog=new Dialog(frame, "警告", false); dialog.setBounds(250, 100, 200, 100); dialog.setLayout(new FlowLayout()); label=new Label(); dialog.add(label); frame.setVisible(true); addEventAction(); } /** * 添加事件 */ public void addEventAction() { // 退出 frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); } }); //对话框的window事件 dialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { dialog.setVisible(false); } }); // action事件 button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String dirName = tf.getText(); File file = new File(dirName); if (!file.isDirectory() || !file.exists()) { dialog.setVisible(true); label.setText(dirName+"目录不存在"); ta.setText("目录不存在"); return; } String[] files = file.list(); StringBuilder sb = new StringBuilder(); for (String name : files) { sb.append(name); sb.append("/r/n"); } ta.setText(sb.toString()); } }); } /** * @param args */ public static void main(String[] args) { new FrameDemo(); } }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/industrynews/12638.html