一、窗体基本使用 JFrame
package Demo;
import javax.swing.*;
import java.awt.*;
public class Demo extends JFrame {
public Demo() {
setVisible(true); //设置窗体对象可见
setTitle("TITLE XXXXX ");
// JFrame.EXIT_ON_CLOSE, 隐藏窗口并停止程序
// JFrame.DO_NOTHING_ON_CLOSE: 点击窗口无任何操作
// JFrame.HIDE_ON_CLOSE : 隐藏窗口, 但不停止程序
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//setSize(400,300); //设置窗体大小为300x200 pixel
//setLocation(600, 300); // 设置窗体显示坐标为 600x300 pixel处
setBounds(600, 300, 400, 300); //设置窗体坐标和大小分别为 (600,300)处, 400x300pixel
Container c = getContentPane(); //获得窗体容器
c.setBackground(Color.YELLOW); //设置背景颜色
JLabel l = new JLabel("__标签 1__");
c.add(l);
//c.remove(l);
c.invalidate(); //验证容器中的组件 , 相当于刷新操作
setContentPane(c); //重新载入容器
setResizable(false);// 设置窗体不允许改变大小
System.out.println("窗口坐标 x=" + getX() + " y=" + getY());
}
public static void main(String[] args) {
new Demo();
/*
JFrame f = new JFrame("Hello,This Is Title ^_^"); // 创建窗体对象
f.setVisible(true); //设置窗体对象可见
// JFrame.EXIT_ON_CLOSE, 隐藏窗口并停止程序
// JFrame.DO_NOTHING_ON_CLOSE: 点击窗口无任何操作
// JFrame.HIDE_ON_CLOSE : 隐藏窗口, 但不停止程序
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//f.setSize(400,300); //设置窗体大小为300x200 pixel
//f.setLocation(600, 300); // 设置窗体显示坐标为 600x300 pixel处
f.setBounds(600, 300, 400, 300); //设置窗体坐标和大小分别为 (600,300)处, 400x300pixel
Container c = f.getContentPane(); //获得窗体容器
c.setBackground(Color.YELLOW); //设置背景颜色
JLabel l = new JLabel("__标签 1__");
c.add(l);
//c.remove(l);
c.invalidate(); //验证容器中的组件 , 相当于刷新操作
f.setContentPane(c); //重新载入容器
f.setResizable(false);// 设置窗体不允许改变大小
System.out.println("窗口坐标 x=" + f.getX() + " y=" + f.getY());
*/
}
}
实现结果如下:
二、对话框窗体 JDialog
package Demo;
import javax.swing.*;
import java.awt.*;
public class Diage extends JDialog {
public Diage(JFrame frame) {
super(frame, "对话框", true); //frame: 父窗体对象 , 对话框标题 , true: 阻塞窗体
Container c = getContentPane(); //获得窗体容器
c.add( new JLabel("对话框^_^") );
setBounds(650, 350, 200, 150); //设置窗体坐标和大小
}
}
---------------------------------------------------------
接着前面窗体的main
public static void main(String[] args) {
Demo De = new Demo();
Container c = De.getContentPane();
//设置布局,使用流布局
c.setLayout(new FlowLayout());
JButton btn = new JButton("弹出对话框");
c.add(btn);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Diage di = new Diage(De); // 点击按纽,弹出对话框
di.setVisible(true); //设置窗体可见
}
}); // 添加动作监听
}