[javaSE] GUI(对话框Dialog)
2023-02-18 15:47:18 时间
对话框不能单独存在,依赖于窗体,有显示标题,有模式
获取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(); } }
相关文章
- Shell编程从看懂到看开①(Shell概述、变量、运算符、条件判断)
- Shell编程从看懂到看开②(字符串、数组、注释、流程控制、read读取控制台输入)
- Shell编程从看懂到看开③(函数、echo、printf、test)
- [SpringBoot系列]任务与邮件
- 【Nginx】初识与环境准备
- LeetCode - #63 不同路径 II
- LeetCode - #64 最小路径和(Top 100)
- LeetCode - #65 有效数字
- LeetCode - #66 加一
- LeetCode - #67 二进制求和
- LeetCode - #68 文本左右对齐
- LeetCode - #69 x 的平方根
- 带你掌握java反序列化漏洞及其检测
- 这几种Java异常处理方法,你会吗?
- 教你用Java7的Fork/Join框架开发高并发程序
- Java变异出现错误:No enclosing instance of type XXX is accessible
- LeetCode - #70 爬楼梯(Top 100)
- LeetCode - #71 简化路径
- LeetCode - #72 编辑距离(Top 100)
- LeetCode - #73 矩阵置零