This is a good opportunity for you to set rounded corners for custom components, for example the following example implements setting rounded corners and margins:
import javax.swing.*;
import java.awt.*;
public class BaseComponent extends JComponent {
private Insets insets;
private int radius = 0;
public BaseComponent() {
}
public BaseComponent(Insets insets, int radius) {
this.insets = insets;
this.radius = radius;
}
@Override
protected void paintComponent(Graphics gr) {
Graphics2D g2 = (Graphics2D) gr.create();
// 背景
if (getBackground() != null && isOpaque()) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL,
Boolean.getBoolean("apple.awt.graphics.UseQuartz") ?
RenderingHints.VALUE_STROKE_PURE : RenderingHints.VALUE_STROKE_NORMALIZE);
g2.setColor(getBackground());
g2.fillRoundRect(0, 0, getWidth(), getHeight(), radius, radius);
}
g2.dispose();
}
/**
* 获取内边距,如果没有调用 {@link #setInsets(Insets)} ,则调用父类的insets,否则就获取设置的内边距
*/
@Override
public Insets getInsets() {
if (insets == null) return super.getInsets();
return insets;
}
public int getRadius() {
return radius;
}
public void setRadius(int radius) {
this.radius = radius;
}
public void setInsets(Insets insets) {
this.insets = insets;
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
BaseComponent c = new BaseComponent();
c.setLayout(new BorderLayout());
c.add(new JLabel("this is a label"));
c.setBackground(Color.ORANGE);
c.setPreferredSize(new Dimension(300,200));
c.setRadius(20);
c.setOpaque(true);
c.setInsets(new Insets(10,10,10,10));
f.getContentPane().setLayout(new FlowLayout());
f.getContentPane().add(c);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}