Swing Hacks 学习笔记

本文介绍了一种为Java Swing菜单项创建阴影效果的方法。通过为弹出菜单的父面板添加自定义边框并设置透明背景实现。具体操作是在BasicPopupMenuUI子类的getPopup()方法中进行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Chapter 1. Basic JComponents

Hack 11. Create Menus with Drop Shadows

Most custom effects require either subclassing a component or messing with graphics overlays. I tried a variety of techniques to create this hack, but I kept coming across the same problem over and over. If I wanted to draw a shadow, I had to change the sizing of each menu item, plus its background, plus the pop-up frame itself. That is a lot of components to manage. It would be a lot simpler if I could tell the components to make themselves a little bit bigger and give me the extra slice of screen real estate to draw in. The solution was right under my nose: the border. Every Swing component can use a custom border, without subclassing, and the border will automatically resize the component to fit. If the border is lopsided, then it will create a kind of shadow effect. Perfect!

Every standard Swing component is actually drawn by a UI helper class, and pop-up menus are no exception. I took the BasicPopupMenuUI in the javax. swing.plaf.basic package and created a subclass called CustomPopupMenuUI (shown in Example 1-25). It only does two things special: adds a custom border to the pop up's parent panel and sets the panel to be transparent.

Note: 

1.when or where we should add the custom border to the parent of the JPopupMenu?

In the getPopup() method of the subclass of BasicPopupMenuUI.

2.The comment of

public static ComponentUI createUI(JComponent c){

throw new Error("ComponentUI.createUI not implemented.");

}

in ComponentUI.java :

Returns an instance of the UI delegate for the specified component. Each subclass must provide its own static createUI method that returns an instance of that UI delegate subclass. If the UI delegate subclass is stateless, it may return an instance that is shared by multiple components. If the UI delegate is stateful, then it should return a new instance per component. The default implementation of this method throws an error, as it should never be invoked.

(this method will be invoked by java reflect system)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值