JButton设置圆角
时间: 2024-05-08 09:20:24 浏览: 18
JButton可以通过设置其Border来实现圆角效果。
以下是一个示例代码:
```
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
public class RoundedButton extends JButton {
public RoundedButton(String text) {
super(text);
setBackground(Color.WHITE);
setForeground(Color.BLACK);
setBorder(new RoundedBorder(10));
}
private class RoundedBorder implements Border {
private int radius;
public RoundedBorder(int radius) {
this.radius = radius;
}
public Insets getBorderInsets(Component c) {
return new Insets(this.radius+1, this.radius+1, this.radius+2, this.radius);
}
public boolean isBorderOpaque() {
return true;
}
public void paintBorder(Component c, Graphics g, int x, int y, int width, int height) {
g.setColor(getForeground());
g.drawRoundRect(x, y, width-1, height-1, radius, radius);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("Rounded Button Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 200);
JPanel panel = new JPanel(new FlowLayout());
panel.add(new RoundedButton("Click me!"));
frame.getContentPane().add(panel);
frame.setVisible(true);
}
}
```
该代码中,我们定义了一个RoundedButton类,继承自JButton。在构造函数中,我们设置了按钮的背景和前景色,并且将按钮的边框设置为一个自定义的RoundedBorder类。
RoundedBorder类实现了Border接口,用于绘制圆角边框。在getBorderInsets方法中,我们返回一个Insets对象,用于指定边框的大小和位置。在paintBorder方法中,我们使用Graphics对象绘制圆角边框。
最后,在main方法中,我们创建了一个JFrame和一个JPanel,并将一个RoundedButton添加到该JPanel中,最后将JPanel添加到JFrame中。运行该程序,可以看到一个带有圆角边框的按钮。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)