title: javaSwing如何把丑丑的标题栏隐藏,并且实现拖动和关闭
date: 2020-06-28
tags:
- java
- 技巧
- swing
categories: - java
- swing
javaSwing如何把丑丑的标题栏隐藏,并且实现拖动和关闭
-
是不是感觉标题栏丑丑的,加上下面这个函数呢?
jFrame.setUndecorated(true); //undecorated - 如果没有启用窗体装饰,则为 true;如果启用了窗体装饰,则 为 false。
-
欧,我的上帝,那该死的边框终于消失了。不过为什么我无法移动他了。
-
于是我们开始思考,如何移动这个边框。
//实现无边框拖拽界面 //监听最初位置 this.addMouseListener(new MouseAdapter() { //给JFrame窗体添加一个鼠标监听 public void mousePressed(MouseEvent e) { //鼠标点击时记录一下初始位置 isDraging = true; xx = e.getX(); yy = e.getY(); } public void mouseReleased(MouseEvent e) { //鼠标松开时 isDraging = false; } }); //时刻更新鼠标位置 this.addMouseMotionListener(new MouseMotionAdapter() { //添加指定的鼠标移动侦听器,以接收发自此组件的鼠标移动事件。如果侦听器 l 为 null,则不会抛 出异常并且不执行动作。 public void mouseDragged(MouseEvent e) { //修改位置 if (isDraging) { //只要鼠标是点击的(isDraging),就时刻更改窗体的位置 int left = getLocation().x; int top = getLocation().y; setLocation(left + e.getX() - xx, top + e.getY() - yy); } } });
-
这个该死的白色窗体终于可以移动了,但是怎么关闭呢。这可是个容易到比吃禁果还容易的问题了,在窗体中加个按钮,给按钮添加个监听,点击按钮时关闭该窗口。如果嫌弃按钮不好看,来个JLabel,选个可爱的关闭图标也可以,不过上帝催我去打牌了,我就没时间了哦。
-
于是我这灵巧的双手开始码好了全部代码,这是一件多么容易的事情呀。
package example; import javax.swing.*; import java.awt.*; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; /** * @杂货店的阿猿 * 微信公众号:杂货猿 */ public class zzzyuan { public static void main(String[] args) { example example = new example(); } static class example extends JFrame{ boolean isDraging; int xx,yy; public example() { this.setLayout(null); this.setSize(500,300); this.setUndecorated(true); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JButton bt_close = new JButton("X"); JButton bt_min = new JButton("一"); bt_close.setBounds(450,0,60,30); bt_min.setBounds(390,0,60,30); this.add(bt_close); this.add(bt_min); //关闭按钮监听 bt_close.addActionListener(e -> { dispose(); }); //小化按钮监听 bt_min.addActionListener(e -> { this.setExtendedState(JFrame.ICONIFIED); }); //实现无边框拖拽界面 //监听最初位置 this.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent e) { isDraging = true; xx = e.getX(); yy = e.getY(); } public void mouseReleased(MouseEvent e) { isDraging = false; } }); //时刻更新鼠标位置 this.addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent e) { //修改位置 if (isDraging) { int left = getLocation().x; int top = getLocation().y; setLocation(left + e.getX() - xx, top + e.getY() - yy); } } }); } } }
-
嫌界面丑可以去看看我的第二篇文章哦,《javaSwing的界面美化及添加背景修改透明度》
} } }); }
}
}
* 嫌界面丑可以去看看我的第二篇文章哦,《javaSwing的界面美化及添加背景修改透明度》
-