java圆形_java 圆形按钮类

这篇博客介绍了如何在Java中创建一个圆形的按钮。通过重写`paintComponent`和`paintBorder`方法来绘制圆,以及利用`Ellipse2D`定义形状以确保点击事件仅在圆形区域内生效。代码示例展示了一个橙色背景的圆形按钮在粉色背景下运行的效果。
摘要由CSDN通过智能技术生成

[java]代码库import java.awt.Color;

import java.awt.Dimension;

import java.awt.FlowLayout;

import java.awt.Graphics;

import java.awt.Shape;

import java.awt.geom.Ellipse2D;

import javax.swing.JButton;

import javax.swing.JFrame;

import javax.swing.JLabel;

/**

* 制作一个圆形的按钮时,需要做两件事: 第一件事是重载一个适当的绘画方法以画出一个圆形。

* 第二件事是设置一些事件使得只有当你点击圆形按钮的范围中的时侯按钮才会作出响应

*/

public class CircleButton extends JButton {

public CircleButton(String label) {

super(label);

// 获取按钮的最佳大小

Dimension size = getPreferredSize();

size.width = size.height = Math.max(size.width, size.height);

setPreferredSize(size);

setContentAreaFilled(false);

}

// 画圆的按钮的背景和标签

protected void paintComponent(Graphics g) {

if (getModel().isArmed()) {

g.setColor(Color.lightGray); // 点击时高亮

} else {

g.setColor(getBackground());

}

// fillOval方法画一个矩形的内切椭圆,并且填充这个椭圆,

// 当矩形为正方形时,画出的椭圆便是圆

g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);

super.paintComponent(g);

}

// 用简单的弧画按钮的边界。

protected void paintBorder(Graphics g) {

g.setColor(Color.white);

// drawOval方法画矩形的内切椭圆,但不填充。只画出一个边界

g.drawOval(0, 0, getSize().width - 1, getSize().height - 1);

}

// shape对象用于保存按钮的形状,有助于侦听点击按钮事件

Shape shape;

public boolean contains(int x, int y) {

if ((shape == null) || (!shape.getBounds().equals(getBounds()))) {

// 构造一个椭圆形对象

shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());

}

// 判断鼠标的x、y坐标是否落在按钮形状内。

return shape.contains(x, y);

}

public static void main(String[] args) {

JButton button = new CircleButton("");

button.setBackground(Color.orange);

JFrame frame = new JFrame("圆形按钮");

frame.getContentPane().setBackground(Color.pink);

frame.getContentPane().setLayout(new FlowLayout());

frame.getContentPane().add(button);

frame.setSize(200, 200);

frame.setVisible(true);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

}

}

[代码运行效果截图]

d4cad7dccdcc4da29f10b5f185cf344a.png

694748ed64b9390909c0d88230893790.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值