Magda
Magda

Reputation: 147

Displaying image in JPanel from NetBeans GUI Builder

I created a JFrame in Netbeans and added a JPanel (automatically declared in non-editable code as private javax.swing.JPanel jPanel1).

I have a button on my form and would like to display an image in the panel upon clicking the button - however I'm not sure what code I need to display the image.

Upvotes: 2

Views: 29470

Answers (2)

Paul Samsotha
Paul Samsotha

Reputation: 208984

Follow these steps

  1. Create new JFrame Form (DUH)
  2. Drag a JPanel to your frame (jPanel1);
  3. Drag a JLabel into that JPanel (jLabel1);

  4. Right - click on your project, and create a new package named "resources". You do this so the image will be imported into your project in the jar

  5. Hightlight your JLabel and open your properties pane

  6. Click on the ... button to the right of the icon property.
  7. Select "External Image", click the ... button to select an image, then click "Import to Project" and click OK
  8. You should see the icon in the frame

  9. Drag a JButton into the frame

  10. Right - click the button, select "Events -> Actions -> actionPerformed"

  11. Go your source code, in your constructor add this

    initComponents();
    jPanel1.setVisible(false);  <------
    
  12. In your actionPerfomed, add this

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)   {                                         
        jPanel1.setVisible(true);   <-------
    } 
    
  13. Run your masterpiece. Try and click the button.

Upvotes: 5

nachokk
nachokk

Reputation: 14413

One possible solution

jPanel1 = new JPanel();
jPanel1.add(new JLabel(new ImageIcon("imagePath")));
jPanel.setVisible(false);
//add this panel to the frame

And then when your button is clicked.

myButton.addActionListener(new ActionListener(){ 
     @Override
     public void actionPerformed(ActionEvent e) {
          jPanel1.setVisible(true);
     }
});

Upvotes: 2

Related Questions