手机版
你好,游客 登录 注册
背景:
阅读新闻

Java Swing的背景图片按比例缩放

[日期:2012-06-18] 来源:Linux社区  作者:zhongweijian [字体:大 中 小]

Java Swing的背景图片按比例缩放

  1. import java.awt.*;  
  2. import java.awt.image.BufferedImage;  
  3. import javax.swing.Icon;  
  4. import javax.swing.ImageIcon;  
  5. import javax.swing.JFrame;  
  6. import javax.swing.JLabel;  
  7.   
  8. public class ScaleIcon implements Icon {  
  9.   
  10.     private BufferedImage i = null;  
  11.     private Icon icon = null;  
  12.   
  13.     public ScaleIcon(Icon icon) {  
  14.         this.icon = icon;  
  15.     }  
  16.   
  17.     @Override  
  18.     public int getIconHeight() {  
  19.         return icon.getIconHeight();  
  20.     }  
  21.   
  22.     @Override  
  23.     public int getIconWidth() {  
  24.         return icon.getIconWidth();  
  25.     }  
  26.   
  27.     public void paintIcon(Component c, Graphics g, int x, int y) {  
  28.         float wid = c.getWidth();  
  29.         float hei = c.getHeight();  
  30.         int iconWid = icon.getIconWidth();  
  31.         int iconHei = icon.getIconHeight();  
  32.   
  33.         Graphics2D g2d = (Graphics2D) g;  
  34.         g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);  
  35.         g2d.scale(wid / iconWid, hei / iconHei);  
  36.         icon.paintIcon(c, g2d, 0, 0);  
  37.     }  
  38.   
  39.     public static void main(String[] args) {  
  40.         ScaleIcon icon = new ScaleIcon(new ImageIcon(ClassLoader.getSystemResource("img/main.jpg")));  
  41.         JLabel label = new JLabel(icon);  
  42.         JFrame frame = new JFrame();  
  43.         frame.getContentPane().add(label, BorderLayout.CENTER);  
  44. //                frame.getContentPane().add(new JButton("click"),BorderLayout.NORTH);   
  45.         frame.setSize(800, 600);  
  46.         frame.setLocationRelativeTo(null);  
  47.         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
  48.         frame.setVisible(true);  
  49.     }  
  50. }  

linux
相关资讯       Java教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款