2012-08-17 81 views
3

如何使BMP填充JPanel?如何使BMP填充JPanel

import java.awt.Dimension; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.Image; 
import java.io.File; 
import java.io.IOException; 

import javax.imageio.ImageIO; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
import javax.swing.SwingUtilities; 

public class BMPPanel extends JPanel { 


    String sciezka; 
    Image image; 
    int skala; 
    int rozdzielczosc; 
    Dimension d; 
    public static int NORMALNA = 0, MALA = 1; 

    public BMPPanel(String sciezka, int skala, int rozdzielczosc) { 
     this.sciezka = sciezka; 
     this.skala = skala; 
     this.rozdzielczosc = rozdzielczosc; 
     super.setMaximumSize(d); 
     this.d = new Dimension(400,400); 
     this.go(); 
    } 
    public BMPPanel(String sciezka, int skala) { 
     this(sciezka,skala,200); 
    } 


    public void go() { 
     try { 
      File input = new File(sciezka); 
      image = ImageIO.read(input); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 



     setPreferredSize(new Dimension(image.getWidth(null), 
       image.getHeight(null))); 
    } 

    @Override 
    public void paintComponent(Graphics g) { 
     super.paintComponents(g); 
     Graphics2D g2d = (Graphics2D) g; 
     g2d.drawImage(image, 0, 0, this); 
    } 

    @Override 
    public void setMaximumSize(Dimension d){ 

    } 



} 
+0

希望這篇【答案】(http://stackoverflow.com/a/11372350/1057230)可能可以幫助您在這個方向: - ) – 2012-08-18 18:16:31

回答

2

您需要回答的第一個問題是您希望保持BMP的寬高比嗎?

如果你不那麼它的那樣簡單

Image scaled = image.getScaledInstance(getWidth() - 1, getHeight() - 1, Image.SCALE_SMOOTH); 

如果沒有,那麼你需要問你自己。我想要「填充」或「適合」圖像嗎?填充將允許圖像溢出面板,但會完全填滿它,適合將確保整個圖像將適合面板,但可能會留下空隙。

有這種answer這是一個讀響應類似的問題