java实用教程——组件及事件处理——对话框(dialog)

本是古典 何须时尚 2022-09-04 12:42 307阅读 0赞

对话框:
在这里插入图片描述
在这里插入图片描述

  1. import java.awt.event.ActionEvent;
  2. import java.awt.event.ActionListener;
  3. import java.awt.*;
  4. import java.awt.event.*;
  5. public class DialogDemo1 {
  6. public static void main(String[] args) {
  7. Frame frame = new Frame("这里测试Dialog");
  8. Dialog d1 = new Dialog(frame, "模式对话框", true);
  9. Dialog d2 = new Dialog(frame, "非模式对话框", false);
  10. Button b1 = new Button("打开模式对话框");
  11. Button b2 = new Button("打开非模式对话框");
  12. //设置对话框的大小和位置
  13. d1.setBounds(20,30,300,400);
  14. d2.setBounds(20,30,300,400);
  15. //给b1和b2绑定监听事件
  16. b1.addActionListener(new ActionListener() {
  17. @Override
  18. public void actionPerformed(ActionEvent e) {
  19. d1.setVisible(true);
  20. }
  21. });
  22. b2.addActionListener(new ActionListener() {
  23. @Override
  24. public void actionPerformed(ActionEvent e) {
  25. d2.setVisible(true);
  26. }
  27. });
  28. //把按钮添加到frame中
  29. frame.add(b1,BorderLayout.NORTH);
  30. frame.add(b2,BorderLayout.SOUTH);
  31. //设置WindowListener,监听用户点击X的动作,如果点击X,则关闭窗口
  32. frame.addWindowListener(new WindowAdapter() {
  33. @Override
  34. public void windowClosing(WindowEvent e) {
  35. //停止当前程序
  36. System.exit(0);
  37. }
  38. });
  39. //设置frame最佳大小并可见
  40. frame.pack();
  41. frame.setVisible(true);
  42. }
  43. }

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

  1. import javax.swing.*;
  2. import java.awt.*;
  3. import java.awt.event.ActionEvent;
  4. import java.awt.event.ActionListener;
  5. import java.awt.event.WindowAdapter;
  6. import java.awt.event.WindowEvent;
  7. public class DialogDemo2 {
  8. public static void main(String[] args) {
  9. Frame frame = new Frame("这里测试Dialog");
  10. //1.创建两个对话框Dialog对象,一个模式的,一个非模式的
  11. Dialog d1 = new Dialog(frame, "模式对话框", true);
  12. //创建一个垂直的Box容器,把一个文本框和一个按钮添加到Box容器中
  13. Box vBox = Box.createVerticalBox();
  14. vBox.add(new TextField(20));
  15. vBox.add(new Button("确认"));
  16. //把Box容器添加到Dialog中
  17. d1.add(vBox);
  18. //2.通过setBounds方法设置Dialog的位置以及大小
  19. d1.setBounds(20,30,300,200);
  20. //3.创建两个按钮
  21. Button b1 = new Button("打开模式对话框");
  22. //4.给这两个按钮添加点击后的行为
  23. b1.addActionListener(new ActionListener() {
  24. @Override
  25. public void actionPerformed(ActionEvent e) {
  26. d1.setVisible(true);
  27. }
  28. });
  29. //5.把按钮添加到frame中
  30. frame.add(b1,BorderLayout.NORTH);
  31. //设置WindowListener,监听用户点击X的动作,如果点击X,则关闭窗口
  32. frame.addWindowListener(new WindowAdapter() {
  33. @Override
  34. public void windowClosing(WindowEvent e) {
  35. //停止当前程序
  36. System.exit(0);
  37. }
  38. });
  39. frame.setBounds(100,100,400,400);
  40. //设置frame最佳大小并可见
  41. frame.pack();
  42. frame.setVisible(true);
  43. }
  44. }

在这里插入图片描述
在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,307人围观)

还没有评论,来说两句吧...

相关阅读