Swing之JFrame窗体,以及Jdialog弹窗的认识

首先来接触一下我们的JFrame窗体


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

class myJFrame extends JFrame{
    public myJFrame(){

        this.setVisible(true);
        this.setBounds(200,200,600,500);
        Container container = this.getContentPane();//设置容器,这是和普通Frame的区别。Frame只需要写this.setBackground就行,
//但是JFrame这里只能先设置一个容器,然后在容器里面修改颜色
        container.setBackground(Color.CYAN);//在容器里面修改颜色
        JLabel label = new JLabel("hello!");
        this.add(label);//将创建的标签加入到JFrame中来
        label.setHorizontalAlignment(SwingConstants.CENTER);//对标签进行居中的处理

        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//设置默认的关闭方式,里面总共有四种参数。
    }
}

public class lesson05 {

    public static void main(String[] args) {
        new myJFrame();
    }

}

然后我们进一步接触弹窗,下面是关于按下按钮出现新的弹窗的事件。

public class lesson06 extends JFrame{
    public lesson06(){
        this.setVisible(true);
        this.setBounds(100,100,800,400);
        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        this.setLayout(null);//这句话意思是采用绝对布局,就是说,位置按你实际设置了在哪就是哪
        Container container = this.getContentPane();//设置容器
        JButton jButton = new JButton("点我出现新的弹窗");
        jButton.setBounds(50,50,200,80);
        jButton.addActionListener(new ActionListener() {//对按钮添加动作事件
            @Override
            public void actionPerformed(ActionEvent e) {
                new MyDialog();//创建一个新的MyDialog类
            }
        });
        container.add(jButton);//加到容器中来

    }

    public static void main(String[] args) {
        new lesson06();
    }
}
class MyDialog extends JDialog{
    public MyDialog(){
        this.setVisible(true);
        this.setLayout(null);
        this.setBounds(50,50,500,500);
        JLabel label1 = new JLabel("hello");
        label1.setBounds(60,60,100,100);
        this.add(label1);
//        this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);这句代码不需要是因为
//弹窗已经设置了默认的关闭方式,如果再加上就会出错。
    }
}
posted on 2022-04-05 20:27  damango  阅读(313)  评论(0编辑  收藏  举报