Swing Jpanel实现圆角的问题
publicclassRoundPanelextendsJPanel{//背景图片privateImageIconimg;//圆角范围privateintarcWidth...
public class RoundPanel extends JPanel { //背景图片 private ImageIcon img; //圆角范围 private int arcWidth; private static final long serialVersionUID = 1L; public RoundPanel(){ } public RoundPanel(String imgPath){ img = new ImageIcon(imgPath); } public RoundPanel(String imgPath,int arcWidth){ this(imgPath); this.arcWidth = arcWidth; } @Override protected void paintComponent(Graphics g) { RoundRectangle2D rect = new RoundRectangle2D.Double(0,0,getWidth(),getHeight(),arcWidth,arcWidth); g.setClip(rect); if(img!=null) g.drawImage(img.getImage(), 0, 0, getWidth(), getHeight(), this); } public static void main(String[] args) { JFrame f = new JFrame(); RoundPanel rp = new RoundPanel("images/login_bg.png",30); rp.setOpaque(false); rp.setBackground(Color.BLACK); rp.setBorder(new LineBorder(Color.red)); JButton btn = new JButton("退出"); rp.add(btn); btn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); f.add(rp); f.setSize(300, 300); f.setUndecorated(true); AWTUtilities.setWindowOpaque(f, false); SwingUtils.run(f); }}
=====================================
出现的效果是:背景图片是圆角的,但后面还有一层白底色,如
======================================================================
这问题我已经找到解决方案,写出来分享一下:把绘制圆角的代码挪一下位置:
public void paint(Graphics g) { RoundRectangle2D rect = new RoundRectangle2D.Double(0,0,getWidth(),getHeight(),arcWidth,arcWidth); g.setClip(rect); if(img!=null) g.drawImage(img.getImage(), 0, 0, getWidth(), getHeight(), this); }
paint() 与paintComponent()的主要区别是:前者是绘制容器,后者是绘制容器内的组件
效果: 展开
=====================================
出现的效果是:背景图片是圆角的,但后面还有一层白底色,如
======================================================================
这问题我已经找到解决方案,写出来分享一下:把绘制圆角的代码挪一下位置:
public void paint(Graphics g) { RoundRectangle2D rect = new RoundRectangle2D.Double(0,0,getWidth(),getHeight(),arcWidth,arcWidth); g.setClip(rect); if(img!=null) g.drawImage(img.getImage(), 0, 0, getWidth(), getHeight(), this); }
paint() 与paintComponent()的主要区别是:前者是绘制容器,后者是绘制容器内的组件
效果: 展开
1个回答
展开全部
final Shape shape = new RoundRectangle2D.Double(0d, 0d, f.getWidth(), f.getHeight(), 50, 50);
f.addComponentListener(new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
f.setShape(shape);
}
});
上面这个能让 JFrame 确实是圆角且透明,但不知为何这个 JPanel 的边框绘制时依然不正确。
更多追问追答
追问
因为有背景图片,所以背景色设置无效!那圆角后面白色区域跟背景色无关,因为我不管怎么设置背景色,它都是白色!
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询