2010-02-09 69 views
5

我正在使用JFrame,并且在我的框架上保留了背景图片。现在的问题是,图像的大小小于框架的大小,所以我必须再次在窗口的空白部分保留相同的图像。如果用户点击最大化按钮,我可能不得不在运行时将图像放在框架的空白区域。任何人都可以告诉我如何做到这一点?java swing背景图片

+2

“我必须在空白部分再次保持相同的图像”没有按对我来说没有意义。你可以用你有什么样的东西和你想要的东西来制作一张图片吗? – 2010-02-09 07:36:23

回答

1

你想要类似Windows桌面的背景图像,当多次使用背景图像而不是调整大小或仅显示它居中?

您只需保留一次图像并在paintComponent方法中多次绘制它。

+0

你能给我一个这样的例子代码。如果你有。这对我很有帮助。请? – Nilesh 2010-02-09 08:45:47

+0

查看finnw的示例 – 2010-02-09 19:29:24

12

听起来好像你在谈论平铺与拉伸,尽管目前还不清楚你想要哪种行为。

这个方案有两个例子:

import java.awt.BorderLayout; 
import java.awt.Graphics; 
import java.awt.Image; 
import java.awt.event.ActionEvent; 
import java.io.IOException; 
import java.net.URL; 

import javax.imageio.ImageIO; 
import javax.swing.AbstractAction; 
import javax.swing.JCheckBox; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Main { 
    public static void main(String[] args) throws IOException { 
     final Image image = ImageIO.read(new URL("http://sstatic.net/so/img/logo.png")); 
     final JFrame frame = new JFrame(); 
     frame.add(new ImagePanel(image)); 
     frame.setSize(800, 600); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setVisible(true); 
    } 
} 

@SuppressWarnings("serial") 
class ImagePanel extends JPanel { 
    private Image image; 
    private boolean tile; 

    ImagePanel(Image image) { 
     this.image = image; 
     this.tile = false; 
     final JCheckBox checkBox = new JCheckBox(); 
     checkBox.setAction(new AbstractAction("Tile") { 
      public void actionPerformed(ActionEvent e) { 
       tile = checkBox.isSelected(); 
       repaint(); 
      } 
     }); 
     add(checkBox, BorderLayout.SOUTH); 
    }; 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     if (tile) { 
      int iw = image.getWidth(this); 
      int ih = image.getHeight(this); 
      if (iw > 0 && ih > 0) { 
       for (int x = 0; x < getWidth(); x += iw) { 
        for (int y = 0; y < getHeight(); y += ih) { 
         g.drawImage(image, x, y, iw, ih, this); 
        } 
       } 
      } 
     } else { 
      g.drawImage(image, 0, 0, getWidth(), getHeight(), this); 
     } 
    } 
} 
+1

非常感谢您的回应其工作... – Nilesh 2010-02-11 07:51:46

+0

嗨,你有任何建议如何平铺图像,而不是拉伸它,以保持图像的质量? – NumenorForLife 2014-05-01 17:44:29

0

另一种方式来平铺图像是TexturePaint

public class TexturePanel extends JPanel { 

    private TexturePaint paint; 

    public TexturePanel(BufferedImage bi) { 
     super(); 
     this.paint = new TexturePaint(bi, new Rectangle(0, 0, bi.getWidth(), bi.getHeight())); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     Graphics2D g2 = (Graphics2D) g; 
     g2.setPaint(paint); 
     g2.fill(new Rectangle(0, 0, getWidth(), getHeight())); 
    } 
}