Java Swing Dialog 弹窗使用教程

一、新建一个带按钮的JFrame 参考教程[跳转]参考代码如下(https://blog.csdn.net/jarvan5/article/details/105621342)

package GUI.Swing.Dialog弹窗;

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

public class Demo extends JFrame {
    private void init() {
        //初始化JFrame
        this.setVisible(true);
        this.setLocation(100, 100);
        this.setSize(700, 500);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        //容器,放东西
        Container contentPane = this.getContentPane();
        //绝对布局
        contentPane.setLayout(null);
        //按钮
        JButton jButton = new JButton("点击弹出一个对话框");
        //水平居中
        jButton.setHorizontalAlignment(SwingConstants.CENTER);
        jButton.setSize(200, 50);
        //按钮添加到容器
        contentPane.add(jButton);
        //添加事件
        jButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //new 弹窗
                new DemoDialog弹窗();

            }
        });

    }

    public static void main(String[] args) {
        new Demo().init();
    }
}

二、新建一个 DemoDialog弹窗.java 用来写弹窗的内容。

1.extends JDialog 继承JDialog
2.其他操作和JFrame(Frame)类似
3.问题:设置居中对按钮无效?待解决?
package GUI.Swing.Dialog弹窗;

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

public class DemoDialog弹窗 extends JDialog {
    //construct method 构造方法初始化弹窗样式
    DemoDialog弹窗(){
        this.setTitle("Dialog弹窗");
        this.setVisible(true);
        this.setLocation(200,200);
        this.setSize(200,250);
        //add one label
        Container contentPane = this.getContentPane();
        JLabel jLabel = new JLabel("再容器中添加标签");
        contentPane.add(jLabel);
        //center 居中
        jLabel.setHorizontalAlignment(SwingConstants.CENTER);


    }
}

三、拓展 自带的几个 弹窗样式.更多

public class Task2 {
	Task2()
	{
		
		String firstName=JOptionPane.showInputDialog("Please input your first name","Jiawen");
		String lastName=JOptionPane.showInputDialog("please input your last name","Deng");
		String fullName=firstName+" "+lastName;
		JOptionPane.showMessageDialog(null, fullName,"YOUR FULL NMAE",JOptionPane.PLAIN_MESSAGE);
			
	}
}

你可能感兴趣的:(Java,GUI)