在Java中编程创建圆边按钮可以通过使用Swing或JavaFX库来实现。下面是使用Swing库的示例代码:
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class RoundedButton extends JButton {
public RoundedButton(String text) {
super(text);
setContentAreaFilled(false);
}
@Override
protected void paintComponent(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(getBackground());
g2.fill(new RoundRectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1, 20, 20));
super.paintComponent(g2);
g2.dispose();
}
@Override
protected void paintBorder(Graphics g) {
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setColor(getForeground());
g2.draw(new RoundRectangle2D.Double(0, 0, getWidth() - 1, getHeight() - 1, 20, 20));
g2.dispose();
}
public static void main(String[] args) {
JFrame frame = new JFrame("Rounded Button Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200, 100);
frame.setLayout(new FlowLayout());
RoundedButton button = new RoundedButton("Click Me");
frame.add(button);
frame.setVisible(true);
}
}
这段代码定义了一个名为RoundedButton
的自定义按钮类,继承自JButton
。在paintComponent
方法中,使用Graphics2D
绘制了一个圆角矩形作为按钮的背景,并调用了父类的paintComponent
方法绘制按钮的文本。在paintBorder
方法中,绘制了圆角矩形的边框。
你可以将以上代码保存为一个Java文件,然后编译运行,即可看到一个圆边按钮的示例窗口。
领取专属 10元无门槛券
手把手带您无忧上云