Swing JButton 圆角边框
时间: 2024-09-26 15:08:24 浏览: 112
Swing中的JButton是一个按钮组件,如果想要让它有圆角边框,你可以通过自定义外观或者使用Java的UI工具包来实现。以下是两个常见的方法:
1. **使用`Border`**:
- 使用`CompoundBorder`或者`TitledBorder`结合`LineBorder`来创建圆角边框。例如:
```java
Border border = BorderFactory.createEmptyBorder(5, 5, 5, 5);
border = BorderFactory.createRoundedRectBorder(new Insets(0, 0, 0, 0), 10); // 设置圆角半径,单位通常是像素
JButton button = new JButton();
button.setBorder(border);
```
2. **使用Laf(Look and Feel)**:
- Java的LookAndFeel允许你改变组件的样式,包括边框。可以尝试更换一个支持圆角边框的look and feel,如`MetalLookAndFeel`或者`NimbusLookAndFeel`。但是这需要设置操作系统主题。
注意,上述代码示例适用于Java Swing环境。如果你正在使用JavaFX,那么创建圆角边框的方式会有所不同。
相关问题
jbutton设置边框为圆角矩形
您可以使用下面这段代码来设置JButton的边框为圆角矩形:
```
jbutton.setBorder(new RoundBorder(20));
```
其中,RoundBorder是自定义的一个类,代码如下:
```
import java.awt.*;
import java.awt.geom.*;
import javax.swing.border.*;
public class RoundBorder implements Border {
private int radius;
public RoundBorder(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) {
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(c.getBackground());
g2.fill(new RoundRectangle2D.Double(x, y, width - 1, height - 1, radius, radius));
g2.setColor(c.getForeground());
g2.draw(new RoundRectangle2D.Double(x, y, width - 1, height - 1, radius, radius));
}
}
```
这样,您就可以把JButton的边框设置为圆角矩形了。
swing button 圆角
Swing按钮(JButton)默认的外观比较方正,如果你想让 Swing 按钮呈现出圆角的效果,你可以通过自定义外观、使用布局设置或直接修改组件样式来实现。以下是几种常见方法:
1. **自定义外观**:
使用 `setBorder` 和 `setRolloverBorder` 方法添加一个自定义的边框,例如 `RoundBorder` 类可以创建圆形边缘。
```java
import javax.swing.BorderFactory;
import javax.swing.border.RoundBorder;
JButton button = new JButton();
button.setBorder(BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(5, 5, 5, 5),
BorderFactory.createRoundBorder(8)));
```
2. **LAYOUT 设置**:
如果你想要在整个窗口应用一致的圆角风格,可以考虑使用 GridBagLayout 或者 GroupLayout,并调整相应的属性来控制整个容器的圆角效果。
3. **修改样式**:
JavaFX 提供了更多的样式定制选项,如果你正在使用 JavaFX 中的 Button,可以通过 CSS 风格化来改变圆角。例如,在`.fx-effect`选择器下设置 `-fx-border-radius` 属性。
```css
.button {
-fx-background-color: white;
-fx-border-radius: 10px;
}
```
阅读全文
相关推荐















