JFrame窗体
public class JFreamTest extends JFrame {
public void CreateJFrame(String title) { // 定义一个CreateJFrame()方法
JFrame jf = new JFrame(title); // 创建一个JFrame对象
Container container = jf.getContentPane(); // 获取一个容器
JLabel jl = new JLabel("这是一个JFrame窗体"); // 创建一个JLabel标签
jl.setHorizontalAlignment(SwingConstants.CENTER);// 使标签上的文字居中
container.add(jl); // 将标签添加到容器中
container.setBackground(Color.white); // 设置容器的背景颜色
jf.setVisible(true); // 使窗体可视,false不可见
jf.setSize(200, 150); // 设置窗体大小
jf.setBounds(200, 150, 100, 100);//设置组件左上角的顶点的坐标,宽度,高度
//jf.setLocation(100, 200);//设置组件左上角的顶点的坐标
// 设置窗体关闭方式
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
//EXIT_ON_CLOSE 退出当前窗口并关闭
//HIDE_ON_CLOSE 当前窗口隐藏
//DISPOSE_ON_CLOSE 隐藏并释放窗口
//DO_NOTHING_ON_CLOSE 无操作
}
public static void main(String args[]) { // 在主方法中调用CreateJFrame()方法
new JFreamTest().CreateJFrame("创建一个JFrame窗体");
}
}
JDialog对话框窗体
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class Demo extends JDialog {
public Demo(JFrame frame) {
super (frame,"对话框标题",true);//父窗体对象,对话框标题,是否阻塞父窗体
Container c=getContentPane();//获取窗口容器
c.add(new JLabel("这是一个对话框"));
//setVisible(true);
setBounds(100, 100,100,100);
}
public static void main(String[] args) {
JFrame f=new JFrame("父窗体");
f.setBounds(50, 50, 300, 300);
Container c=f.getContentPane();
JButton btn=new JButton("弹出对话框");
c.setLayout(new FlowLayout());//设置使用流体布局
c.add(btn);
f.setVisible(true);
f.setDefaultCloseOperation(EXIT_ON_CLOSE);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Demo d=new Demo(f);
d.setVisible(true);
}
});//添加动态监听
}
}