swing 初级学习(一)

 jframe 最大、最小、关闭功能

1、屏蔽

 

 现在我们创建一个类并继承于JFrame,
public class DecoratedFrame extends JFrame {
public DecoratedFrame() {
   this.getContentPane().add(new JLabel("Just a test."));
   this.setUndecorated(true); // 去掉窗口的装饰
   this.getRootPane().setWindowDecorationStyle(JRootPane.NONE); //采用指定的窗口装饰风格
   this.setSize(300,150);
}
public static void main(String[] args) {
   JFrame frame = new DecoratedFrame();
   frame.setVisible(true);
}
}


     请看加了注释的两行,要去掉标题栏,关键代码就是这两行,第1行去掉窗口的装饰,第2行为窗口指定头饰风格。在这里,可以通过调用this.getRootPane().setWindowDecorationStyle()方法为窗口指定以下的装饰风格:

NONE                  无装饰(即去掉标题栏)
FRAME                 普通窗口风格
PLAIN_DIALOG          简单对话框风格
INFORMATION_DIALOG    信息对话框风格
ERROR_DIALOG          错误对话框风格
COLOR_CHOOSER_DIALOG 拾色器对话框风格
FILE_CHOOSER_DIALOG   文件选择对话框风格
QUESTION_DIALOG       问题对话框风格
WARNING_DIALOG        警告对话框风格

在使用Jframe的时候,普遍都会有标题栏,还有最小化,最大化,关闭按纽的,还要实现拖动窗体的功能。
这样的话,对我们实现自定义样式的窗体是很有影响的,

1) 要去掉标题栏:
jFrame.setUndecorated(true);
// 这样就可以去掉Jframe中对window的装饰了,

2) 去掉标题栏,我们就有可能要给程序写代码提供最小化,最大化,关闭的操作,如何实现?
只要给按纽添加MouseListener,
在mouseClick中的调用

jFrame.setExtendedState(jFrame.ICONIFIED); //最小化

if(jFrame.getExtendedState() != jFrame.MAXIMIZED_BOTH)
jFrame.setExtendedState(jFrame.MAXIMIZED_BOTH);
else
jFrame.setExtendedState(jFrame.NORMAL);
// 最大化或正常状态

System.exit(0);
// 关闭,退出程序

3) 要拖动窗体的功能:
只要给窗体中的某个组件添加如下代码就行了:

    Point loc = null;    Point tmp = null;    boolean isDragged = false;    private void setDragable() {        this.addMouseListener(new java.awt.event.MouseAdapter() {            public void mouseReleased(java.awt.event.MouseEvent e) {               isDragged = false;               jFrame.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));            }            public void mousePressed(java.awt.event.MouseEvent e) {               tmp = new Point(e.getX(), e.getY());               isDragged = true;               jFrame.setCursor(new Cursor(Cursor.MOVE_CURSOR));            }        });        this.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {            public void mouseDragged(java.awt.event.MouseEvent e) {               if(isDragged) {                   loc = new Point(jFrame.getLocation().x + e.getX() - tmp.x,                     jFrame.getLocation().y + e.getY() - tmp.y);                   jFrame.setLocation(loc);               }            }        }); }  在初始化该组件的时候调用 setDragable() 就可以使组件具体拖放窗体的功能了。因为可能有背景图,可能会重写paint方法,不能在paint方法中调用setDragable()

2、事件

this.addWindowListener(new WindowAdapter(){
            //捕获窗口关闭事件
            public void windowClosing(WindowEvent e){            
              //窗口关闭时的相应处理操作
            }
            //捕获窗口最小化事件
            public void windowIconified(WindowEvent e){
                //窗口最小化时的相应处理操作

            }
        });

 

 

你可能感兴趣的:(swing)