14.Swing’s JFrame form

Swing

AWT only has brushes, but Swing can draw pictures, and it can also do drop-down boxes, selection boxes, and a series of more advanced things.

window, panel

 1 package com.gui.lesson4;
 2 
 3 import javax.swing.*;
 4 import java.awt.*;
 5
 6 public class JFrameDemo {
 7
 8 //init(); initialization
 9 public void init() {
10 //Top-level window
11 JFrame jf = new JFrame("This is a JFrame window");
12 jf.setVisible(true);
13 jf.setBounds(100, 100, 200, 200);
14 jf.setBackground(Color.cyan);
15 //Set text Jlabel
16 JLabel label = new JLabel("Welcome to King of Glory");
17
18 jf.add(label);
19
20 //Close event, set the default shutdown operation. No need to write the listener yourself.
21 jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
twenty two 
twenty three     }
twenty four 
25 public static void main(String[] args) {
26 //Create a window
27 new JFrameDemo().init();
28 }
29}

View Code

The color is not changed because swing has the concept of a container:

 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 //Set text JLabel
19 JLabel label = new JLabel("Welcome to the King of Glory");
20 this.add(label);
twenty one 
22 //JLabel text is centered and horizontal alignment is set
23 label.setHorizontalAlignment(SwingConstants.CENTER);
twenty four 
25 //Get a container
26 Container container = this.getContentPane();
27 container.setBackground(Color.yellow);
28 }
29}

View Code