Frame窗体
注意点就是JFrame的需要用Container的转化一下为容器。下面代码用到了JLabel(标签组件)。
import java.awt.*;
import javax.swing.*;
public class Example extends JFrame{
public void CreateJFrame(String title){
JFrame jf = new JFrame(title);
Container container =jf.getContentPane();
JLabel jl = new JLabel("Frame窗口");//标签组件
jl.setHorizontalAlignment(SwingConstants.CENTER);
container.add(jl);
container.setBackground(Color.white);//背景颜色
jf.setVisible(true);//窗体可视
jf.setSize(200,150);//窗体尺寸
jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public static void main(String args[]){
new Example().CreateJFrame("创建一个JFrame窗口");
}
}
运行后就这样,这个挫东西让我高兴半天。
关闭方式(手写笔记超过一次,这里偷懒截图算辽)
JDialog窗体
JDialog窗体就是对话框。也需要用getContentPane转换为容器。
class MyJDialog extends JDialog{
public void MyDialog(MyFrame frame){
super(frame,"小弹窗",true);
Container container =getContentPane();
container.add(new JLabel("这是一个对话框"));
setBounds(120,120,100,100);
}
}
public class MyFrame extends JFrame{
public static void main(String args[])
{
new MyFrame();//实例化MyJDialog类对象
}
public MyFrame() {
Container container = getContentPane();//创建容器
container.setLayout(null);
JLabel man = new JLabel("Java Study");//窗体标签
man.setHorizontalAlignment(SwingConstants.CENTER);
container.add(man);
JButton bl= new JButton("点我");
bl.setBounds(20,20,100,21);
bl.addActionListener(new ActionListener() {//为按钮添加事件
public void actionPerformed(ACtionEvent e) {
new MyJDialog(MyFrame.this).setVisible(true);
}
});
container.add(bl);
//我也不知道少了啥明天再改改
}
}