Reputation: 147
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
Reputation: 208984
Follow these steps
Drag a JLabel into that JPanel (jLabel1);
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
Hightlight your JLabel and open your properties pane
icon
property.You should see the icon in the frame
Drag a JButton into the frame
Right - click the button, select "Events -> Actions -> actionPerformed"
Go your source code, in your constructor add this
initComponents();
jPanel1.setVisible(false); <------
In your actionPerfomed, add this
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jPanel1.setVisible(true); <-------
}
Run your masterpiece. Try and click the button.
Upvotes: 5
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