Swing
AWT只有画笔,但是Swing能画图,它还能做一些下拉框,选择框等等一系列更高级的东西
窗口、面板
1 package com.gui.lesson4; 2 3 import javax.swing.*; 4 import java.awt.*; 5 6 public class JFrameDemo { 7 8 //init(); 初始化 9 public void init() { 10 //顶级窗口 11 JFrame jf = new JFrame("这是一个JFrame窗口"); 12 jf.setVisible(true); 13 jf.setBounds(100, 100, 200, 200); 14 jf.setBackground(Color.cyan); 15 //设置文字 Jlabel 16 JLabel label = new JLabel("欢迎来到王者荣耀"); 17 18 jf.add(label); 19 20 //关闭事件,设置默认的关闭操作。不用自己写监听器了。 21 jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 22 23 } 24 25 public static void main(String[] args) { 26 //建立一个窗口 27 new JFrameDemo().init(); 28 } 29 }
颜色没上去,因为swing有个容器的概念:
1 package com.gui.lesson4; 2 3 import javax.swing.*; 4 import java.awt.*; 5 6 public class JFrameDemo2 { 7 public static void main(String[] args) { 8 new MyJFrame2().init(); 9 } 10 } 11 12 class MyJFrame2 extends JFrame { 13 public void init() { 14 15 this.setBounds(10, 10, 200, 200); 16 this.setVisible(true); 17 18 //设置文字 JLabel 19 JLabel label = new JLabel("欢迎来到王者荣耀"); 20 this.add(label); 21 22 //JLabel文字居中,设置水平对齐 23 label.setHorizontalAlignment(SwingConstants.CENTER); 24 25 //获得一个容器 26 Container container = this.getContentPane(); 27 container.setBackground(Color.yellow); 28 } 29 }