Java基础学习第三十一天(容器组件、非容器组件、布局管理器、事件)

一、容器组件

1、java使用到的图形类主要在java.awt 与javax.swing包中。

2、java.awt 与 javax.swing包的区别:
① java.awt中使用的图形类都是依赖于系统的图形库的。
② javax.swing包使用到的图形类都是sun自己实现,不需要依赖系统的图形库。

3、在java中所有的图形类都被称作组件类。
组件的类别:容器组件、非容器组件
组件类

public class Demo31.1{
    public static void main(String[] args) {
        JFrame frame = new JFrame("这个是我第一个图形化界面的例子");
        //设置窗体的大小
        frame.setSize(300,400);

        //设置窗体(左上角)出现的位置
        //frame.setBounds((1366-300)/2,(768-400)/2,300,400); //第一个参数是左上角的x轴坐标,第二参数是左上角y的坐标,第三个窗体宽,第四窗体的高

        initFrame(frame,300,400);
        frame.setVisible(true); //setVisible设置窗体的可见性。
        //设置窗体关闭事件
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
    //获取屏幕的分辨率,设置窗体在屏幕的居中位置
    public static void initFrame(JFrame frame,int width,int height){
        Toolkit toolkit = Toolkit.getDefaultToolkit(); //获取一个与系统相关工具类对象
        //获取屏幕的分辨率
        Dimension d = toolkit.getScreenSize();
        int x = (int) d.getWidth();
        int y = (int) d.getHeight();
        frame.setBounds((x-width)/2, (y-height)/2, width, height);  
    }
}
//初始化窗体的工具类
public class FrameUtil {
    public static void initFrame(JFrame frame,int width , int height){
        Toolkit toolkit = Toolkit.getDefaultToolkit(); //获取一个与系统相关工具类对象
        //获取屏幕的分辨率
        Dimension d = toolkit.getScreenSize();

        int x = (int) d.getWidth();
        int y = (int) d.getHeight();

        frame.setBounds((x-width)/2, (y-height)/2, width, height);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

4、对话框类(Dialog)
① JDialog(Dialog owner, String title, boolean modal)
owner: 所有者
title : 标题
modal : 模式
② JOptionPane(对话框)
消息对话框、警告对话框、错误对话框、输入对话框、确认对话框

public class Demo31.2 {
    public static void main(String[] args) {
        JFrame frame = new JFrame("窗体");
        //创建对话框
        JDialog dialog = new JDialog(frame,"对话框",true);
        //使用我自定义的窗体工具类FrameUtil
        FrameUtil.initFrame(frame, 300, 400);       
        dialog.setBounds(500,300, 100, 200);
        dialog.setVisible(true); //设置对话框的可见性    

        JFrame frame = new JFrame("窗体");
        //显示一个对话框
        FrameUtil.initFrame(frame, 300, 400);
        //消息对话框
        JOptionPane.showMessageDialog(frame,"明天放假","通知",JOptionPane.INFORMATION_MESSAGE);
        //警告对话框
        JOptionPane.showMessageDialog(frame,"警告实验室禁止打游戏","警告",JOptionPane.WARNING_MESSAGE);
        //错误对话框
        JOptionPane.showMessageDialog(frame,"扣100分","错误",JOptionPane.ERROR_MESSAGE);    
        //输入框
        String moeny = JOptionPane.showInputDialog("请输入经销商代码:");
        System.out.println("code:"+ cade);  
        //确认框
        int num = JOptionPane.showConfirmDialog(frame,"你确认要卸载吗?");
        System.out.println(num);
    }   
}

5、文件对话框(FileDialog)
FileDialog(Dialog parent, String title, int mode)
parent: 对话框的所有者
tiltle : 对话框的标题
mode: load(打开) 、 save(保存)

public class Demo31.3 {
    public static void main(String[] args) {
        JFrame frame = new JFrame("窗体");
        //创建一个文件对话框(初始也是不可见)

        FileDialog fileDialog = new FileDialog(frame, "请选择打开的文件", FileDialog.LOAD);

        FileDialog fileDialog = new FileDialog(frame,"请选择保存的路径",FileDialog.SAVE);

        FrameUtil.initFrame(frame, 300,400);
        fileDialog.setVisible(true);
        System.out.println("文件所在的目录:"+ fileDialog.getDirectory());
        System.out.println("文件名:"+ fileDialog.getFile());   
    }   
}

6、面板(JPanel)

public class Demo31.4 { 
    public static void main(String[] args) {
        JFrame frame = new JFrame("窗体");
        //创建一个面板
        JPanel panel = new JPanel();
        //设置面板的背景颜色
        panel.setBackground(Color.RED);
        //把面板添加到窗体
        frame.add(panel);
        FrameUtil.initFrame(frame, 400, 300);   
    }   
}

二、非容器组件

public class Demo31.5 {
    public static void main(String[] args) {
        JFrame frame= new JFrame("注册界面");
        //创建一个面板
        JPanel panel = new JPanel();
        frame.add(panel); 
        //用户名
        JLabel nameLabel = new JLabel("用户名");
        //用户名的输入框
        JTextField nameField = new JTextField(12);
        //把用户名的组件添加到面板上
        panel.add(nameLabel);
        panel.add(nameField);   
        //密码
        JLabel passLabel= new JLabel("密码");
        //密码框
        JPasswordField passField = new JPasswordField(12);
        //把密码的组件添加到面板
        panel.add(passLabel);
        panel.add(passField);   
        //性别:单选框
        JLabel sexLabel = new JLabel("性别");
        JRadioButton man = new JRadioButton("男",true);
        JRadioButton woman = new JRadioButton("女");
        //如果是单选框必须要进行分组,同一个组的单选框只能选择其中的一个
        ButtonGroup group = new ButtonGroup();
        group.add(woman);
        group.add(man);
        //把性别组件添加到面板上
        panel.add(sexLabel);
        panel.add(man);
        panel.add(woman);   
        //来自城市:下拉框
        JLabel cityLabel = new JLabel("来自的城市");
        Object[] arr = {"北京","上海","广州","深圳","江苏"};
        JComboBox citys = new JComboBox(arr);
        panel.add(cityLabel);
        panel.add(citys);
        //兴趣爱好:复选框
        JLabel hobitLabel = new JLabel("兴趣爱好:");
        JCheckBox checkBox1 = new JCheckBox("篮球",true);
        JCheckBox checkBox2 = new JCheckBox("java",true);
        JCheckBox checkBox3 = new JCheckBox("javascript");
        JCheckBox checkBox4 = new JCheckBox("android");
        panel.add(hobitLabel);
        panel.add(checkBox1);
        panel.add(checkBox2);
        panel.add(checkBox3);
        panel.add(checkBox4);
        //个人简介
        JLabel jLabel = new JLabel("个人简介");
        JTextArea area = new JTextArea(20, 15);//20行15列
        area.setLineWrap(true); //设置自动换行 
        panel.add(jLabel);
        panel.add(area);    
        FrameUtil.initFrame(frame, 500, 400);
    }
}
public class Demo31.6 {
    JFrame frame = new JFrame("记事本");
    //菜单条
    JMenuBar bar = new JMenuBar();
    //文件菜单
    JMenu fileMenu = new JMenu("文件");
    JMenu editMenu  = new JMenu("编辑");
    JMenu switchMenu = new JMenu("切换工作目录");
    //菜单项
    JMenuItem openMenu = new JMenuItem("打开");
    JMenuItem saveMenu = new JMenuItem("保存");
    JMenuItem aboutMenu = new JMenuItem("关于");
    JMenuItem closeMenu = new JMenuItem("关闭");
    JMenuItem  workMenu1 = new JMenuItem("0910project");
    JMenuItem  workMenu2 = new JMenuItem("1208project");
    JMenuItem  workMenu3 = new JMenuItem("1110project");
    JTextArea area = new JTextArea(20,30);
    public void initNotepad(){
        //菜单添加菜单项目
        fileMenu.add(openMenu);
        fileMenu.add(saveMenu);
        editMenu.add(aboutMenu);
        editMenu.add(closeMenu);    
        //复选菜单
        switchMenu.add(workMenu1);
        switchMenu.add(workMenu2);
        switchMenu.add(workMenu3);
        //菜单添加菜单就是复选菜单
        fileMenu.add(switchMenu);   
        //菜单条添加菜单
        bar.add(fileMenu);
        bar.add(editMenu);  
        //添加菜单条
        frame.add(bar,BorderLayout.NORTH);
        frame.add(area);
        FrameUtil.initFrame(frame, 500, 600);
    }   
    public static void main(String[] args) {
        new Demo31.6().initNotepad();
    }   
}

三、布局管理器

1、布局管理器:布局管理就是用于指定组件的摆放位置的。

2、BorderLayout(边框布局管理器)
摆放的风格: 上北 、 下南 、 左西、 右东 , 中

3、Borderlayout 要注意的事项:
① 使用Borderlayout添加组件的时候,如果没有指定组件的方位,那么默认添加到中间的位置上
② 使用BorderLayout的时候,如果东南西北那个方向没有对应的组件,那么中间位置的组件就会占据其空缺的位置
③ 窗体默认的布局管理器就是Borderlayout

public class Demo31.7{
    public static void main(String[] args) {
        JFrame frame = new JFrame("边框局部管理器");
        //创建一个边框布局管理器
        BorderLayout borderLayout = new BorderLayout();
        //让borderlayout管理frame窗体
        frame.setLayout(borderLayout);
        frame.add(new JButton("北"),BorderLayout.NORTH);
        frame.add(new JButton("南"),BorderLayout.SOUTH);
        frame.add(new JButton("西"),BorderLayout.WEST);
        frame.add(new JButton("东"),BorderLayout.EAST);
        frame.add(new JButton("中"),BorderLayout.CENTER);
        //初始化窗体
        FrameUtil.initFrame(frame, 300, 300);
    }
}

4、流式布局管理器(FlowLayout)
流式布局管理器要注意的事项
① 流式布局管理器默认情况是居中对齐的
② panel默认的局部管理器就是FlowLayout

public class Demo31.8 {
    public static void main(String[] args) {
        JFrame frame = new JFrame("窗体");
        //创建面板
        JPanel panel = new JPanel();
        frame.add(panel);
        //创建一个流式布局管理器,指定对齐的方式为FlowLayout.LEFT,水平间隙为0,垂直间隙为30
        FlowLayout flowLayout = new FlowLayout(FlowLayout.LEFT, 0, 30); 
        //让流式布局管理器管理frame窗体
        panel.setLayout(flowLayout);    
        panel.add(new JButton("按钮1"));
        panel.add(new JButton("按钮2"));
        panel.add(new JButton("按钮3"));
        panel.add(new JButton("按钮4"));  
        //初始化窗体
        FrameUtil.initFrame(frame, 300, 300);   
    }
}

5、表格布局管理器(GridLayout)
注意的事项: 如果表格数量不够使用时,默认会多加一列。

public class Demo31.9 {
    public static void main(String[] args) {
        JFrame frame = new JFrame("计算器");
        //创建表格布局管理器
        GridLayout gridLayout = new GridLayout(4, 4, 1, 2);//4行4列,水平间隙为1,垂直间隙为2
        //让窗体交给表格布局管理器管理
        frame.setLayout(gridLayout);
        for(int i = 0 ; i<10; i++){
            frame.add(new JButton(i+""));
        }
        frame.add(new JButton("+"));
        frame.add(new JButton("-"));
        frame.add(new JButton("*"));
        frame.add(new JButton("/"));
        frame.add(new JButton("="));
        frame.add(new JButton("."));        
        //初始化窗体
        FrameUtil.initFrame(frame, 300, 300);   
    }
}

6、卡片布局管理器(CardLayout)

public class Demo31.10{
    public static void main(String[] args) {
        JFrame frame = new JFrame("卡片布局管理器");
        final JPanel panel = new JPanel();
        frame.add(panel);   
        //创建一个卡片布局管理器
        final CardLayout cardLayout = new CardLayout();
        panel.setLayout(cardLayout);    
        //往面板添加数据
        JButton button = new JButton("黑桃A");
        panel.add(button);
        panel.add(new JButton("红桃A"));
        panel.add(new JButton("梅花A"));
        panel.add(new JButton("方块A"));
        button.addActionListener(new ActionListener() { 
            @Override
            public void actionPerformed(ActionEvent e) {
                cardLayout.next(panel);  //下一张
                //cardLayout.previous(parent);  //上一张
            }
        });
        //初始化窗体
        FrameUtil.initFrame(frame,300, 300);    
    }
}

四、事件

1、事件(包括事件源、监听器、处理方案):当发生了某件事情时候会有相应的处理方案

public class Demo31.11{
    public static void main(String[] args) {
        JFrame frame = new JFrame("窗体");
        JButton button = new JButton("点我啊");
        frame.add(button);
        //给按钮添加动作监听器,动作时间监听器对于鼠标点击以及空格键都会起作用的

        button.addActionListener(new ActionListener() {     
            //当按钮被点击的时候,就会调用actionPerformed的方法
            @Override
            public void actionPerformed(ActionEvent e) {  // ActionEvent当前按钮被点击的时候,jvm就会把对应的时间传递ActionEvent,并且调用actionPerformed方法
                JButton button =(JButton) e.getSource();                   
                //getSource() 获取到事件源
                if(button.getText().equals("点我啊")){
                    button.setText("开始点击");
                }else{
                    button.setText("你已经点过了");
                }           
            }
        }); 

        FrameUtil.initFrame(frame, 200, 200);   
    }
}

2、鼠标事件监听器

public class Demo31.12 {
    public static void main(String[] args) {
        JFrame frame = new JFrame("鼠标事件监听器");
        JButton button = new JButton("按钮");
        frame.add(button);

        /**
        //给按钮添加鼠标事件监听器
        button.addMouseListener(new MouseListener() {   
            @Override
            public void mouseReleased(MouseEvent e) {
                System.out.println("鼠标松开...");
            }

            @Override
            public void mousePressed(MouseEvent e) {
                System.out.println("鼠标按下..");
            }

            @Override
            public void mouseExited(MouseEvent e) {
                System.out.println("鼠标移出...");
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                System.out.println("鼠标进入...");
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("鼠标单击...");
            }
        });
        **/

        //添加鼠标监听器的时候我只使用到单击事件,但是目前要我实现所有的方法??
        //解决方案:适配器。适配器是实现了MouseListener方法的所有方法,但是实现的方法全部都是空实现
        button.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                System.out.println("鼠标单击了..");
                if(e.getClickCount()==2){
                    System.out.println("鼠标双击了..");
                }   
            }               
        });

        FrameUtil.initFrame(frame, 300, 300);       
    }   
}

3、 键盘事件监听器

public class Demo3 {
    public static void main(String[] args) {
        JFrame frame = new JFrame("键盘事件监听器");
        JButton button = new JButton("按钮");
        frame.add(button);

        /**
        //给按钮添加键盘事件监听器
        button.addKeyListener(new KeyListener() {   
            @Override
            public void keyTyped(KeyEvent e) {
                System.out.println("键入某个键");
            }

            @Override
            public void keyReleased(KeyEvent e) {
                System.out.println("释放某个键");
            }

            @Override
            public void keyPressed(KeyEvent e) {
                System.out.println("按下某个键");
            }
        });
        **/

        button.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                System.out.println("按下的字符:"+e.getKeyChar());
                System.out.println("获取键对应的数值:"+ e.getKeyCode());
                int code = e.getKeyCode();
                switch (code) {
                case 38:
                    System.out.println("上");
                    break;
                case 40:
                    System.out.println("下");
                    break;
                case 37:
                    System.out.println("左");
                    break;
                case 39:
                    System.out.println("右");
                    break;
                default:
                    break;
                }
            }
        });

        FrameUtil.initFrame(frame,300, 300);    
    }
}

4、作业

public class FileSearch {
    JFrame frame = new JFrame("文件搜索器");
    JPanel panel = new JPanel();
    JTextField field = new JTextField("请输入目录名...",15);
    JButton button = new JButton("搜索");
    JTextArea area = new JTextArea(15,15);
    //滚动条
    ScrollPane bar = new ScrollPane();
    public void init(){
        //先把area添加到滚动条上
        bar.add(area);
        //先把组件添加到panel上
        panel.add(field);
        panel.add(button);  
        //给输入框添加事件
        field.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JTextField field =  (JTextField) e.getSource();
                if(field.getText().equals("请输入目录名...")){
                    field.setText("");
                }
            }
        });

        //给按钮添加事件监听器
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //获取输入框输入的路径
                String path = field.getText();
                //使用输入的路径构建一个FIle对象
                File dir = new File(path);
                //找到目录下的所有子文件
                File[] files = dir.listFiles();
                for(File file : files){ // 1208Project  资料
                    area.setText(area.getText()+ file.getName()+"\r\n");
                }
            }
        });

        //把面板添加到frame上
        frame.add(panel,BorderLayout.NORTH);
        frame.add(bar);     
        FrameUtil.initFrame(frame, 300, 400);
    }
    public static void main(String[] args) {
        new FileSearch().init();    
    }
}
public class Notepad {
    JFrame frame = new JFrame("记事本");
    //菜单条
    JMenuBar bar = new JMenuBar();
    //文件菜单
    JMenu fileMenu = new JMenu("文件");
    JMenu editMenu  = new JMenu("编辑");
    JMenu switchMenu = new JMenu("切换工作目录");
    //菜单项
    JMenuItem openMenu = new JMenuItem("打开");
    JMenuItem saveMenu = new JMenuItem("保存");
    JMenuItem aboutMenu = new JMenuItem("关于");
    JMenuItem closeMenu = new JMenuItem("关闭");
    JMenuItem  workMenu1 = new JMenuItem("0910project");
    JMenuItem  workMenu2 = new JMenuItem("1208project");
    JMenuItem  workMenu3 = new JMenuItem("1110project");
    TextArea area = new TextArea(20,30);
    public void initNotepad(){
        //菜单添加菜单项目
        fileMenu.add(openMenu);
        fileMenu.add(saveMenu); 
        //给保存添加事件
        saveMenu.addActionListener(new ActionListener() {   
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    FileDialog fileDialog = new FileDialog(frame, "请选择保存的路径",FileDialog.SAVE);
                    fileDialog.setVisible(true);
                    //获取用户选择的路径与文件名
                    String path = fileDialog.getDirectory();
                    String fileName = fileDialog.getFile();
                    //创建一个输入对象
                    FileOutputStream fileOutputStream = new FileOutputStream(new File(path,fileName));

                    //获取文本域的内容,把内容写出
                    String content = area.getText();
                    content = content.replaceAll("\n", "\r\n");
                    fileOutputStream.write(content.getBytes());
                    //关闭资源
                    fileOutputStream.close();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }   
            }
        });
        editMenu.add(aboutMenu);
        editMenu.add(closeMenu);
        //复选菜单
        switchMenu.add(workMenu1);
        switchMenu.add(workMenu2);
        switchMenu.add(workMenu3);
        //菜单添加菜单就是复选菜单
        fileMenu.add(switchMenu);
        //菜单条添加菜单
        bar.add(fileMenu);
        bar.add(editMenu);
        //添加菜单条
        frame.add(bar,BorderLayout.NORTH);
        frame.add(area);
        FrameUtil.initFrame(frame, 500, 600);
    }   
    public static void main(String[] args) {
        new Notepad().initNotepad();
    }   
}

猜你喜欢

转载自blog.csdn.net/Mr_GaoYang/article/details/81386110