2017-06-17 53 views
0

讓我問你一個問題。我有一個包含不同大小圖片的文件夾,我隨機讀取一張圖片,縮小它的大小並在jpanel上使用JLabel進行推演 - 這很簡單。事實上,一幅畫的撤回可以顯示在正確的座標上,另一幅可以反彈在米上。爲什麼會發生?隨機照片忽略SetBounds和其他容器的邊界。輸出到屏幕時圖像的位置不正確

private void initialize() throws IOException { 
    frame = new JFrame(); 
    frame.setBounds(100, 100, 1150, 664); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    frame.getContentPane().setLayout(null); 
    panel = new JPanel(); 
    panel.setBounds(10, 10, 1150, 664); 
    frame.getContentPane().add(panel); 

    File f = new File ("C:/Users/user/Desktop/Ramms"); 
    String[] names = f.list(); 
    all_Images= new ImageIcon[names.length]; 
    for(int i=0; i<names.length; i++){ 
     all_Images[i]= new ImageIcon ("C:/Users/user/Desktop/Ramms/"+names[i]); 
    } 
    selected_Image = all_Images[random(0,all_Images.length)]; 
    w= selected_Image.getIconWidth()/scl; 
    h= selected_Image.getIconHeight()/scl; 
    Image img = selected_Image.getImage(); 
    bic = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); 
    Graphics g = bic.createGraphics(); 
    g.drawImage(img, 0, 0, w, h, null); 
    newIcon = new ImageIcon(bic); 
    panel.setLayout(null); 

    JLabel label1 = new JLabel(newIcon); 
    panel.add(label1).setBounds(0,100,w,h);   
} 
+2

1)爲了更好地幫助越早,張貼[MCVE]或[簡要,獨立的,正確的示例](http://www.sscce.org/)。 2)獲取圖像的一種方法是通過[本問答](http://stackoverflow.com/q/19209650/418556)中的圖像進行熱鏈接。 –

+1

請勿使用空佈局。 Swing旨在與佈局經理一起使用。 – camickr

回答

2

減小其尺寸

看起來不像你正在減少其大小對我說:

bic = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB); 
Graphics g = bic.createGraphics(); 
g.drawImage(img, 0, 0, w, h, null); 
newIcon = new ImageIcon(bic); 

Icon的大小是創建BufferedImage的大小。

它不知道或不在乎你在BufferedImage上繪製什麼。

一對夫婦的解決方案:

  1. 當您創建BufferedImage你需要在它的規模大小來創建圖像。

  2. 使用Image.getScaledInstance(...)方法調整圖像大小。