GUI
在java中,java.awt.*包和javax.swing包,用于定义GUI相关的组件类。
在GUI中采用先进先出的原则,越先添加的组件越在上层
窗口创建步鄹
//产生窗体对象
JFrame jFrame = new JFrame();
//设置窗体大小
jFrame.setSize(600, 400);
//设置窗体的可见程度
jFrame.setVisible(true);
//设置窗体关闭,程序结束
jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//设置窗体相对于居中
jFrame.setLocationRelativeTo(null);
//设置窗体的标题
jFrame.setTitle("我的窗体");
创建标签组件
//设施布局管理器,null布局的特点是,以组件的位置和大小来定位组件
this.setLayout(null);
//创建一个标签组件
JLabel jLabel=new JLabel("姓名");
//设置标签的位置和大小
jLabel.setBounds(100,10,100,20);
JLabel jLabel=new JLabel("姓名");
jLabel.setBounds(100,30,100,20);
jFrame.add(jLabel);
创建按钮组件
//创建按钮组件
JButton jButton=new JButton("确定");
jButton.setBounds(50,130,60,40);
this.add(jButton);
创建文本框组件
//创建文本框组件
JTextField jTextField=new JTextField();
jTextField.setBounds(140,50,120,20);
this.add(jTextField);
创建密码框组件
//创建密码框
JPasswordField jPasswordField=new JPasswordField();
jPasswordField.setBounds(300,50,50,20);
this.add(jPasswordField);
字体设置
JLabel jLabel = new JLabel("学生管理系统");
jLabel.setBounds(50, 50, 250, 40);
this.add(jLabel);
//设置字体的大小
jLabel.setFont(new Font("宋体", Font.BOLD, 30));
//设置前景色(字体颜色)
jLabel.setForeground(Color.RED);
//设置透明度
jLabel.setOpaque(true);
//设置后景色(背景色)
jLabel.setBackground(Color.YELLOW);
插入图片
JLabel jLabel1=new JLabel();
jLabel1.setBounds(0,0,900,600);
// this.add(jLabel1);
// jLabel1.setIcon(new ImageIcon("src\\HomeWork4_3\\Frame\\Picture\\3gQwfbo-arxwXjZ5aT3cS1ht-20e.jpg.medium.jpg"));
//将图像缩放成指定大小
Image image=new ImageIcon("src\\HomeWork4_3\\Frame\\Picture\\3gQwfbo-arxwXjZ5aT3cS1ht-20e.jpg.medium.jpg").getImage();
image=image.getScaledInstance(900,600,1);
jLabel1.setIcon(new ImageIcon(image));
this.add(jLabel1);
复选框
//复选框
JCheckBox jCheckBox=new JCheckBox("你同意协议吗");
jCheckBox.setBounds(500,50,160,50);
this.add(jCheckBox);
jCheckBox.setFont(new Font("宋体",Font.BOLD,20));
this.setSize(900, 600);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setTitle("我的窗体");
下拉框
//下拉框
JComboBox jComboBox = new JComboBox(new String[]{"初中", "高中", "大专", "本科"});
jComboBox.setBounds(400, 200, 150, 20);
this.add(jComboBox);
换行
JLabel jl = new JLabel("<html>为中华之崛<br>起而读书</html>");
jl.setBounds(50, 50, 300, 200);
jl.setFont(new Font("宋体",Font.BOLD,20));
add(jl);
添加小容器
JPanel jP=new JPanel();
jP.setBounds(50,250,300,300);
jP.setLayout(null);
//设置小容器的边框
jP.setBorder(BorderFactory.createLineBorder(Color.red));
add(jP);
添加按钮
JButton b=new JButton("确定");
b.setBounds(30,30,80,20);
jP.add(b);