工具类–很常用,可以获取屏幕信息,还可以操作图标图片
设置标题
this.setTitle(“我的第一个GUI程序。”);
设置图标
this.setIconImage(tk.createImage(“pic” + File.separator + “14.jpg”));
尺寸初始化
this.setSize(500, 400);
位置设置
this.setLocation(((int)(tk.getScreenSize().getWidth())-500)/2, ((int)(tk.getScreenSize().getHeight()) - 400)/2);
设置窗体大小不可变
this.setResizable(false);
关闭窗体即设置为关闭程序
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
设置窗体可见–一定放到构造方法的最后一句
this.setVisible(true);
内容面板上的东西
获取内容面板
this.contentP = this.getContentPane();
this.contentP.setBackground(new Color(162,234,149));
this.contentP.setBackground(Color.WHITE);
设置内容面板的布局管理器为null—使用绝对定位的方式放置组件
this.contentP.setLayout(null);
放置文本标签
this.nameLab = new JLabel();//产生对象
this.nameLab.setText("用户名:");//设置文本
this.nameLab.setFont(new Font("华文楷体",Font.ITALIC,28));//设置字体
this.nameLab.setForeground(Color.GREEN);//设置前景色
this.nameLab.setBounds(30, 50, 130, 30);//设置位置和大小
this.contentP.add(this.nameLab);//放入容器
放置图像标签
this.imageLab = new JLabel();//产生对象
this.imageLab.setIcon(new ImageIcon("pic/eye.JPG"));//放置图片
this.imageLab.setBounds(165, 50, 298, 50);//设置图片位置和大小
this.contentP.add(this.imageLab);//将图片标签放入容器
文本框
this.nameTxt = new JTextField();//产生文本框对象
this.nameTxt.setFont(new Font("宋体",Font.BOLD,22));//设置字体
this.nameTxt.setForeground(Color.BLUE);//设置背景色
this.nameTxt.setBounds(30, 105, 120, 30);//设置文本框的大小以及位置
this.contentP.add(this.nameTxt);//将文本框放入容器
密码框
this.pwdTxt = new JPasswordField();//产生密码框对象
this.pwdTxt.setFont(new Font("宋体",Font.BOLD,22));//设置密码框文字的字体格式
this.pwdTxt.setForeground(Color.BLUE);//设置背景色
this.pwdTxt.setEchoChar('*');//设置密码框的回显字符
this.pwdTxt.setBounds(160, 105, 120, 30);//设置大小以及位置
this.contentP.add(this.pwdTxt);//放入容器中
下拉框
this.genderCom = new JComboBox(new Object[]{"男","女"});//产生下拉框对象
this.genderCom.addItem("太监");//添加选项
this.genderCom.setSelectedIndex(2);//指定默认被选中项
this.genderCom.setEditable(true);//设置是否可被编辑
this.genderCom.setBounds(300, 105, 120, 30);//设置大小以及位置
this.contentP.add(this.genderCom);//放入容器中
按钮
this.okBtn = new JButton();//产生按钮对象
this.okBtn.setText("确定");//设置按钮的名字
this.okBtn.setIcon(new ImageIcon("pic/hp.JPG"));//设置默认图标
this.okBtn.setRolloverIcon(new ImageIcon("pic/xiaoxin.GIF")); //设置鼠标移动进去的图标
this.okBtn.setBounds(30, 140, 100, 30);//设置位置以及大小
this.contentP.add(this.okBtn);//放入容器
单选框
this.maleRad = new JRadioButton();//产生单选框对象
this.maleRad.setText("男");//设置单选框的名字
this.femaleRad = new JRadioButton();//产生单选框对象
this.femaleRad.setText("女");//设置单选框的名字
this.femaleRad.setSelected(true);//设置被选中为真
this.maleRad.setBounds(140, 140, 50, 20);//设置maleRad单选框的位置
this.femaleRad.setBounds(200, 140, 50, 20);//设置femaleRad单选框的位置
this.contentP.add(this.maleRad);//将maleRad对象放入容器中
this.contentP.add(this.femaleRad);//将femaleRad对象放入容器中
//按钮组--是一个逻辑概念,将放入其中的按钮在逻辑上进行分组
ButtonGroup bg = new ButtonGroup();
bg.add(this.maleRad);
bg.add(this.femaleRad);
文本域
this.contentArea = new JTextArea();//产生文本域对象
this.scrollP = new JScrollPane(contentArea);//产生滚动条
this.scrollP.setBounds(30, 180, 440, 180);设置位置以及大小
this.contentP.add(this.scrollP);//放入容器中