你不能在实际的JLabel区域上圆角;它们总是长方形的.但是,一个简单的替代方法是将JLabel的ImageIcon设置为具有圆边的图像,而不是使用边框.要设置ImageIcon:
yourLabel.setIcon(new ImageIcon(getClass().getResource("/path/to/your/image.png"));
// Note: Relative path, starts from root of project
您的图像应具有JLabel的尺寸.
请注意,如果找不到图像,这将抛出NullPointerException.确保你找到正确的道路!
要创建一个调整大小为JLabel大小的ImageIcon:
ImageIcon ico = new ImageIcon("/path/to/your/image.png");
Image img = ico.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.drawImage(img, 0, 0, yourLabel.getWidth(), yourLabel.getHeight(), null);
IconImage newIco = new IconImage(bi);
yourLabel.setIcon(newIco);
编辑:
这是使用Graphics2D制作圆角边框的最佳方法.
首先,创建一个名为RoundedBorder的新类.将此代码粘贴到其中: