帮我重启一个swing按钮,要求为圆角,并且鼠标移动到按钮上面会改变按钮颜色
时间: 2023-09-04 13:08:39 浏览: 100
java swing JButton 圆角按钮 鼠标监听变色(有注释简单易懂可直接运行)
好的,为您提供一个简单的示例代码:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class RoundedButton extends JButton {
public RoundedButton(String text) {
super(text);
setOpaque(false);
setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15));
addMouseListener(new MouseAdapter() {
@Override
public void mouseEntered(MouseEvent e) {
setBackground(new Color(225, 225, 225));
}
@Override
public void mouseExited(MouseEvent e) {
setBackground(UIManager.getColor("control"));
}
});
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(getBackground());
g2.fillRoundRect(0, 0, getWidth(), getHeight(), 20, 20);
g2.dispose();
super.paintComponent(g);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(120, 40);
}
}
```
您可以将此代码复制粘贴到一个新的类中,然后在您的代码中创建此类的实例并将其添加到您的swing界面中。
阅读全文