TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
任意形状的按钮制作:

- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- public class AnyShapeButton extends JButton{
- Polygon shape;
- // 任意 shape 按钮构造函数
- public AnyShapeButton(Polygon p) {
- init(p);
- }
- // 任意 shape 按钮构造函数
- public AnyShapeButton(int[] y,int[] x) {
- Polygon p = new Polygon(x,y,x.length);
- init(p);
- }
- private void init(Polygon p){
- shape = p;
- setOpaque(false);
- setPreferredSize();
- setBorder(null);
- // hot tracking process
- addMouseListener(new MouseAdapter(){
- public void mouseEntered(MouseEvent e) {
- Hot();
- }
-
- public void mouseExited(MouseEvent e) {
- Normal();
- }
- });
- }
- public void setPreferredSize() {
- Rectangle b = shape.getBounds(); // 取得 shape 最大外框
- setPreferredSize(new Dimension(b.width, b.height)); // 配置目前组件的宽高, 以方便 Layout 作业
- }
- public void Hot(){
- curColor=java.awt.Color.yellow;
- repaint();
- }
- public void Normal(){
- curColor=java.awt.Color.red;
- repaint();
- }
- // 画出组件的内容: 验证组件的 shape 确实如设计一般
- java.awt.Color curColor=java.awt.Color.red;
- public void paintComponent(Graphics g ) {
- g.setColor(curColor);
- g.fillPolygon(shape);
- }
- // 提供 UI 决定鼠标是否落在组件的内部
- public boolean contains(int x, int y ) {
- return shape.contains(x,y);
- }
- }
复制代码 另一个文件:Main.java请下载。
源码下载:http://file.javaxxz.com/2014/11/12/235721187.zip |
|