使用SWING编写没有修饰栏的窗口

    我想很多人都想过使用JAVA编写没有修饰栏的窗口了吧,所谓没有修饰栏就是没有关闭,最小化,最大化等按钮。 很多尝试过的人或许已经知道Window ,JWindow类可以实现这个需求,但是毕竟他们都是很底层的一个container有时候并不满足我们的需求。我将要讲的将是继承JFrame来实现的。

 代码如下:

 

public class MainFrame extends JFrame implements {

	/**

	 * Create the frame

	 */

	public MainFrame() {

		super();

		getContentPane().setBackground(new Color(128, 128, 192));

		setTitle("Media Player");

		setUndecorated(true);//建立无标题修饰栏的关键代码,这句代码一定要先于窗口动作的所有语句前执行,比如setVisible(),pack()等方法。

		setBounds(100, 100, 500, 375);

		setLayout(null);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//

	}



}

 这样我们就建立了一个没有标题修饰栏的窗口了 。但是没有了标题栏,我们要如何移动这个窗口呢?很简单我们只需要为我们的窗口添加两个事件监听器MouseListener,MouseMotionListener.并重写两个方法public void mouseDragged(MouseEvent parm1)和public void mousePressed(MouseEvent parm1)

完整的实例代码如下:

public class MainFrame extends JFrame implements MouseListener,

		MouseMotionListener {

	private static final long serialVersionUID = -6258202046510672036L;



	private Point startPoint;



	private Point startLocation;



	/**

	 * Create the frame

	 */

	public MainFrame() {

		super();

		getContentPane().setBackground(new Color(128, 128, 192));

		setTitle("Media Player");

		setUndecorated(true);

		setBounds(100, 100, 500, 375);

		setLayout(null);

		addMouseListener(this);

		addMouseMotionListener(this);

		System.out.println();

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

		//

	}



	public void mouseDragged(MouseEvent parm1) {

		startLocation = getLocation();

		setLocation(startLocation.x - startPoint.x + parm1.getPoint().x,

				startLocation.y - startPoint.y + parm1.getPoint().y);

		Toolkit.getDefaultToolkit().sync();

	}



	public void mousePressed(MouseEvent parm1) {

		startPoint = parm1.getPoint();

	}



	public void mouseMoved(MouseEvent arg0) {

	}



	public void mouseClicked(MouseEvent arg0) {

	}



	public void mouseEntered(MouseEvent arg0) {

	}



	public void mouseExited(MouseEvent arg0) {

	}



	public void mouseReleased(MouseEvent arg0) {

	}



}
好了现在我们可以写一个包含Main()的测试类来测试我们的成果了 
public class Main {



	/**

	 * @param args

	 */

	public static void main(String[] args) {

		try {

			MainFrame frame = new MainFrame();

			frame.setVisible(true);

		} catch (Exception e) {

			e.printStackTrace();

		}

	}



}
其中涉及的包请自己添加import语句。
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值