2016-10-05 5 views
-1

をNetbeansでJPanelに表示する必要があります。 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(); 

しかし、それはパネル上の画像を描いていません。私はいくつかのチュートリアルに従ってきましたが、全く作業していません。 BufferedImageJPanelに表示する正しい例を挙げることはできますか?

/* 
* 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)BTW - アプリケーションリソースはデプロイメント時に埋め込まれたリソースになるので、今のようにアクセスすることをお勧めします。 [タグ:埋め込みリソース]は、ファイルではなくURLでアクセスする必要があります。 [info。埋め込みリソースのページ](http://stackoverflow.com/tags/embedded-resource/info)を参照してください。 –

+0

論理的には、 'catch'の終了後のすべてのコードは' try'コードブロック内になければなりません。なぜなら、 'try'が失敗すると失敗するからです。 –

+0

'img = ImageHelper.loadImage(path);'コードをIDE内の新しいプロジェクトにコピーして貼り付け、コンパイルしてみてください。次に、イメージを読み込む 'ImageHelper'クラスが見つからないことがあります。おそらく、すべてのコードの唯一の関連部分です。もう一度.. MCVEを投稿してください!画像を取得する方法の1つは、[このQ&A](http://stackoverflow.com/q/19209650/418556)に表示されている画像にホットリンクすることです。 BTW - イメージをロードして表示するには、200行を超えるコードを使用すべきではありません。 40のLOCトップイメージをロードするだけに、問題を絞り込むためにもっと努力してください! –

答えて

1

あなたが目に見えるGUIにコンポーネントを追加すると、基本的なコードは次のとおりです、あなたがそれ以外の成分が(0の大きさを有することができ、レイアウトマネージャを起動するために再検証が必要

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

0 )ので、塗装するものはありません。

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

ただし、大きな問題は、GroupLayoutを使用していて、GroupLayoutに制約を指定していないことです。制約と実際の例については、How to Use GroupLayoutのSwingチュートリアルを読んでください。

個人的には、コンポーネントをフレームに動的に追加する場合は、コードジェネレータ(およびGroupLayout)を取り除き、GUIレイアウトを作成することをお勧めします。あなたの "imagePlace"パネルでFlowLayoutを使って始めてください。制約は必要ないので、コードははるかに簡単になります。

関連する問題