JDialog窗体的功能是从一个窗体弹出另外一个窗体。
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class MyJDialog extends JDialog {
public MyJDialog(MyFrame frame){
//实例化一个JDialog类对象,指定对话框的父窗体、窗体标题和类型
super(frame, "the first JDialog", true);
Container container = getContentPane();//创建容器
container.add(new Label("this is a Label!"));//在容器中添加标签
setBounds(120, 120, 120, 120);//设置对话框的大小
}
}
public class MyFrame extends JFrame{
public static void main(String args[]){
new MyFrame();//实例化MyJDialog类对象
}
public MyFrame(){
Container container = getContentPane();//创建一个容器
container.setLayout(null);
JLabel jl = new JLabel("this is a label!");//在窗体中设置标签
jl.setHorizontalAlignment(SwingConstants.CENTER);//标签文字居中
container.add(jl);
JButton jb = new JButton("this is a button, you can click it!");//定义按钮
jb.setBounds(10,10,100,21);
jb.addActionListener(new ActionListener() {//为按钮添加鼠标单击事件
@Override
public void actionPerformed(ActionEvent e) {
new MyJDialog(MyFrame.this).setVisible(true);//使MyJDialog窗体可见
}
});
container.add(jb);//将按钮加入容器
container.setBackground(Color.white);//设置容器的背景
setVisible(true);//使窗体可见
setSize(200, 150);//窗体大小
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//设置窗体的关闭方式
}
}