GUI基础 | 您所在的位置:网站首页 › 组件容器delphi › GUI基础 |
简介
图形用户界面(Graphics User InterFace) java.awt.*包和javax.swing包,用于定义GUI相关的组件类 awt是使用操作系统本身提供组件风格来构建java的gui组件。所以在跨平台时,显示风格不一样 为了弥补awt类包的不足,swing包中awt包的基础上,增加了自己的显示风格,这样在跨平台的时候,显示风格会保持一致,swing包的很多组件类都继承了awt包中的组件类 GUI开发流程建立容器 ----- 容器就是可以容纳其他图形对象的类,容器中还可以添加容器 设置容器布局的布局管理器 ----- 设置容器中组件的排列方式 建立组件 ----- 组件就是一套图形对象 将组件添加到容器 ------ 将创建好的对象添加到容器中,才能在窗体上正式显示 Swing容器类 JFrameJFrame类是java.awt.Frame类的扩展,是顶级容器,也就是只能向JFrame中添加组件,但不能用容器添加JFrame 即便中程序中已经有其他容器时,也往往是将其他容器添加到JFrame中 public class MyJFrame extends JFrame { public MyJFrame(){ //设置布局管理器为绝对布局,以组件位置和大小定位组件 //设置为null为绝对布局,组件以容器窗体左上角为原点进行位置设置 this.setLayout(null); //设置窗体大小位置 this.setSize(600 宽 , 400 高); //居中 this.setLocationRelativeTo(null); //设置窗体可见 this.setVisible(true); //设置窗体关闭,程序结束 this.setDefaultCloseOperation(EXIT_ON_CLOSE); } } Swing组件综述Swing包含一套图形对象,用来辅助窗体完成与用户的互交功能,组件通常要添加到容器中 常用Swing组件 JTextField ---- 单行文本域 JButton ---- 按钮 JLabel ---- 标签 初始化组件 private void init(){ //添加按钮组件 //1.创建按钮组件 JButton addButton = new JButton("这是一个添加按钮"); //2.设置按钮组件的尺寸及窗体中的位置 addButton.setBounds(100,100,200,30); //3.将组件添加到窗体上 this.add(addButton); } private void init(){ //添加按钮组件 //1.创建按钮组件 JButton addButton = new JButton("这是一个添加按钮"); //2.设置按钮组件的尺寸及窗体中的位置 addButton.setBounds(200,100,200,30); addButton.setBackground(Color.yellow); //3.将组件添加到窗体上 this.add(addButton); JTextArea jTextField = new JTextArea(); jTextField.setBackground(Color.white); jTextField.setBounds(200,200,200,100); this.add(jTextField); JLabel jLabel = new JLabel("东拉西扯"); jLabel.setBackground(Color.red); jLabel.setBounds(50,50,200,100); this.add(jLabel); } Swing图片组件 //获取图片对象 ImageIcon image = new ImageIcon("src/preview.jpg"); //基于图片对象创建图片标签 JLabel imgLabel = new JLabel(image); imgLabel.setBounds(0,0,image.getIconWidth(),image.getIconHeight()); this.add(imgLabel); 委托事件模型 事件监听接口ActionListener ---- 行为监听接口 ItemListener ---- 选项监听接口 KeyListener ---- 键盘监听接口 MouseListener ---- 鼠标点击监听接口 事件委托模型实现步骤建立事件源对象 如:各种GUI组件 为事件源对象选择合适的事件监听器 如:按钮点击事件,选择ActionListener 键盘事件 选择KeyListener 为监听器添加适当的处理程序,绑定事件发生后,完成的业务操作 为监听器与事件源建立联系 ActionListener MyJButton addButton = new MyJButton("删除",0,0,this); public class MyPress implements ActionListener { @Override public void actionPerformed(ActionEvent e) { System.out.println("按钮被点击"); } } //为事件源对象 绑定 监听器 addButton.addActionListener(new MyPress()); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { jLabel2.setText(Integer.parseInt(jLabel2.getText())+1+""); } }); //等价于 login.addActionListener(e -> { dispose(); new Login(400,500); }); |
CopyRight 2018-2019 实验室设备网 版权所有 |