Swing

Swing

窗口,面板

package com.lean.Lession04;

import javax.swing.*;

public class JFrameDemo {
     
    //init();初始化
    public void init(){
     
        JFrame jFrame = new JFrame("这是一个JFrame窗口");
        jFrame.setVisible(true);
        jFrame.setBounds(100,100,400,100);

        //设置文字 Jlable
        JLabel label = new JLabel("加油冒险家");

        jFrame.add(label);
        //容器实例化


        //关闭事件
        jFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {
     
        //建立一个窗口
        new JFrameDemo().init();
    }
}

标签文字居中

package com.lean.Lession04;

import javax.swing.*;
import java.awt.*;

public class JFrameDemo02 {
     
    public static void main(String[] args) {
     
        new MyJframe2().init();
    }
}
class MyJframe2 extends JFrame{
     
   public void init(){
     
       this.setVisible(true);
       this.setBounds(100,200,200,200);

       JLabel label = new JLabel("加油冒险家");
       this.add(label);
       //让文本居中
       label.setHorizontalAlignment(SwingConstants.CENTER);

       //获得一个容器
       Container container = this.getContentPane();
        container.setBackground(Color.blue);
   }

}


弹窗

JDialog 用来被弹出,默认就有关闭

package com.lean.Lession04;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class DialogDemo extends JFrame {
     
    public DialogDemo(){
     
        this.setVisible(true);
        this.setBounds(200,200,700,500);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        //JFrame 放东西,容器
        Container container = this.getContentPane();

        //绝对布局,就是将坐标写死
        container.setLayout(null);

        //按钮
        JButton button = new JButton("召唤对话框");//创建
        button.setBounds(300,50,200,50);

        //点击这个按钮的时候,弹出一个弹窗
        button.addActionListener(new ActionListener() {
     
            //监听器
            @Override
            public void actionPerformed(ActionEvent e) {
     
                //弹窗
                new  MyDialogDemo();
            }
        });
        container.add(button);

    }
    public static void main(String[] args) {
     
        new DialogDemo();
    }
}
//弹窗的窗口
class MyDialogDemo extends JDialog{
     
    public MyDialogDemo() {
     
        this.setVisible(true);
        this.setBounds(100,100,500,500);
        //多余了this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        Container container = this.getContentPane();
        container.setLayout(null);

        container.add(new Label("前方就是宝藏!"));
    }
}

你可能感兴趣的:(Swing)