2016-10-05 110 views
-1

我需要使用Netbeans在JPanel上顯示BufferedImage。我使用Netbeans的拖放來添加面板。然後我添加了代碼以在面板上顯示圖像。這是我的代碼:在JPanel上顯示BufferedImage

BufferedImage img = null; 
try { 
    img = ImageHelper.loadImage(path); 
} catch (IOException ex) { 
    Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex); 
} 
ImageIcon icon = new ImageIcon(img); 
JLabel picLabel = new JLabel(icon); 

//imagePlace is JPanel 
imagePlace.add(picLabel); 
imagePlace.repaint(); 

但它沒有在面板上畫圖像。我遵循了一些教程,但根本沒有工作。你能舉一個例子來顯示BufferedImage的正確方法JPanel

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 
package tubes; 

import java.awt.BorderLayout; 
import java.awt.Graphics; 
import java.awt.Graphics2D; 
import java.awt.image.BufferedImage; 
import java.io.File; 
import java.io.IOException; 
import java.util.logging.Level; 
import java.util.logging.Logger; 
import javax.swing.ImageIcon; 
import javax.swing.JFileChooser; 
import javax.swing.JLabel; 
import static jdk.nashorn.tools.ShellFunctions.input; 

/** 
* 
* @author ivan 
*/ 
public class MainGUI extends javax.swing.JFrame { 

/** 
* Creates new form MainGUI 
*/ 
public MainGUI() { 
    initComponents();   
} 

/** 
* This method is called from within the constructor to initialize the form. 
* WARNING: Do NOT modify this code. The content of this method is always 
* regenerated by the Form Editor. 
*/ 
@SuppressWarnings("unchecked") 
// <editor-fold defaultstate="collapsed" desc="Generated Code">       
private void initComponents() { 

    jTabbedPane1 = new javax.swing.JTabbedPane(); 
    jPanel1 = new javax.swing.JPanel(); 
    openImageBtn = new javax.swing.JButton(); 
    imagePlace = new javax.swing.JPanel(); 
    canvas1 = new java.awt.Canvas(); 
    jPanel2 = new javax.swing.JPanel(); 

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); 

    jPanel1.setPreferredSize(new java.awt.Dimension(512, 512)); 

    openImageBtn.setText("Open Image"); 
    openImageBtn.addActionListener(new java.awt.event.ActionListener() { 
     public void actionPerformed(java.awt.event.ActionEvent evt) { 
      openImageBtnActionPerformed(evt); 
     } 
    }); 

    imagePlace.setBackground(new java.awt.Color(254, 254, 254)); 

    javax.swing.GroupLayout imagePlaceLayout = new javax.swing.GroupLayout(imagePlace); 
    imagePlace.setLayout(imagePlaceLayout); 
    imagePlaceLayout.setHorizontalGroup(
     imagePlaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGap(0, 178, Short.MAX_VALUE) 
    ); 
    imagePlaceLayout.setVerticalGroup(
     imagePlaceLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGap(0, 194, Short.MAX_VALUE) 
    ); 

    canvas1.setBackground(new java.awt.Color(255, 0, 0)); 

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); 
    jPanel1.setLayout(jPanel1Layout); 
    jPanel1Layout.setHorizontalGroup(
     jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(jPanel1Layout.createSequentialGroup() 
      .addContainerGap() 
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(jPanel1Layout.createSequentialGroup() 
        .addComponent(openImageBtn) 
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) 
       .addGroup(jPanel1Layout.createSequentialGroup() 
        .addComponent(imagePlace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 253, Short.MAX_VALUE) 
        .addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) 
        .addGap(80, 80, 80)))) 
    ); 
    jPanel1Layout.setVerticalGroup(
     jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(jPanel1Layout.createSequentialGroup() 
      .addContainerGap() 
      .addComponent(openImageBtn) 
      .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
       .addGroup(jPanel1Layout.createSequentialGroup() 
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) 
        .addComponent(imagePlace, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) 
       .addGroup(jPanel1Layout.createSequentialGroup() 
        .addGap(96, 96, 96) 
        .addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) 
      .addContainerGap(144, Short.MAX_VALUE)) 
    ); 

    jTabbedPane1.addTab("tab1", jPanel1); 

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); 
    jPanel2.setLayout(jPanel2Layout); 
    jPanel2Layout.setHorizontalGroup(
     jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGap(0, 523, Short.MAX_VALUE) 
    ); 
    jPanel2Layout.setVerticalGroup(
     jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGap(0, 387, Short.MAX_VALUE) 
    ); 

    jTabbedPane1.addTab("tab2", jPanel2); 

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); 
    getContentPane().setLayout(layout); 
    layout.setHorizontalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(layout.createSequentialGroup() 
      .addGap(20, 20, 20) 
      .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 535, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap(108, Short.MAX_VALUE)) 
    ); 
    layout.setVerticalGroup(
     layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) 
     .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() 
      .addContainerGap(25, Short.MAX_VALUE) 
      .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 430, javax.swing.GroupLayout.PREFERRED_SIZE) 
      .addContainerGap()) 
    ); 

    pack(); 
}// </editor-fold>       

private void openImageBtnActionPerformed(java.awt.event.ActionEvent evt) {            
    // TODO add your handling code here: 
    JFileChooser fileChooser = new JFileChooser(); 
    fileChooser.setCurrentDirectory(new File(System.getProperty("user.home"))); 
    int result = fileChooser.showOpenDialog(this); 
    if (result == JFileChooser.APPROVE_OPTION) { 
     File selectedFile = fileChooser.getSelectedFile(); 
     String path = selectedFile.getAbsolutePath(); 
     System.out.println(path); 
     BufferedImage img = null; 
     try { 
      img = ImageHelper.loadImage(path); 
     } catch (IOException ex) { 
      Logger.getLogger(MainGUI.class.getName()).log(Level.SEVERE, null, ex); 
     } 
     ImageIcon icon = new ImageIcon(img); 
     JLabel label = new JLabel("", icon, JLabel.CENTER); 
     JLabel picLabel = new JLabel(icon); 
     imagePlace.add(picLabel); 
     imagePlace.repaint(); 
    } 
}            

/** 
* @param args the command line arguments 
*/ 
public static void main(String args[]) { 
    /* Set the Nimbus look and feel */ 
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> 
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. 
    * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
    */ 
    try { 
     for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { 
      if ("Nimbus".equals(info.getName())) { 
       javax.swing.UIManager.setLookAndFeel(info.getClassName()); 
       break; 
      } 
     } 
    } catch (ClassNotFoundException ex) { 
     java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (InstantiationException ex) { 
     java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (IllegalAccessException ex) { 
     java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } catch (javax.swing.UnsupportedLookAndFeelException ex) { 
     java.util.logging.Logger.getLogger(MainGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); 
    } 
    //</editor-fold> 

    /* Create and display the form */ 
    java.awt.EventQueue.invokeLater(new Runnable() { 
     public void run() { 
      new MainGUI().setVisible(true); 
     } 
    }); 
} 

// Variables declaration - do not modify      
private java.awt.Canvas canvas1; 
private javax.swing.JPanel imagePlace; 
private javax.swing.JPanel jPanel1; 
private javax.swing.JPanel jPanel2; 
private javax.swing.JTabbedPane jTabbedPane1; 
private javax.swing.JButton openImageBtn; 
// End of variables declaration     
} 
+0

1)爲了更好地提供幫助,請發佈[MCVE]或[簡短,獨立,正確的示例](http://www.sscce.org/)。 2)順便說一句 - 應用程序資源在部署時將成爲嵌入式資源,所以現在開始訪問它們是明智的。 [tag:embedded-resource]必須通過URL而不是文件訪問。請參閱[信息。頁面爲嵌入式資源](http://stackoverflow.com/tags/embedded-resource/info)如何形成的URL。 –

+0

從邏輯上講,'catch'結束後的所有代碼應該位於'try'代碼塊內,因爲如果'try'失敗將會失敗。 –

+0

'img = ImageHelper.loadImage(path);'嘗試將代碼複製/粘貼到IDE中的新項目並編譯它。然後你可能會注意到加載圖像的'ImageHelper'類缺失。它可能是所有代碼中唯一相關的部分。所以再次..發佈一個MCVE!獲取圖像的一種方法是通過[本問答](http://stackoverflow.com/q/19209650/418556)中的圖像進行熱鏈接。順便說一句 - 它不應該採取> 200行代碼來加載和顯示圖像。 40個LOC頂部。花更多的精力將問題縮小到僅僅載入圖像! –

回答

1

當你將組件添加到一個可見的GUI的基本代碼是:

imagePlace.add(imgpnl); 
    imagePlace.revalidate(); //added 
    imagePlace.repaint(); 

你需要重新驗證調用佈局管理器,否則該組件可能的大小爲(0,0 )所以沒有什麼可以繪畫的。

javax.swing.GroupLayout imagePlaceLayout = new javax.swing.GroupLayout(imagePlace); 
imagePlace.setLayout(imagePlaceLayout); 

然而,更大的問題是,你正在使用的GroupLayout和你沒有指定的GroupLayout任何約束。有關約束和工作示例的信息,請閱讀How to Use GroupLayout上的Swing教程。

就個人而言,如果您想動態添加組件到框架,我建議您擺脫代碼生成器(和GroupLayout)並自己創建GUI佈局。首先在您的「imagePlace」面板上使用FlowLayout。代碼將會更簡單,因爲您不需要任何約束。