This is a Java Program to Create a Button and Display Image in the Frame when Clicked.
We have to write a program in Java such that it creates a frame with a button. When the button is clicked an image is displayed in the frame.
To display image on click of button, we have the following set of input and output.
To Display the Image on Click:
If an image "logo.jpeg" is available in the present working directory, then it is expected that the frame displays the image when user clicks on display button.
Sample Image :
1. Create a frame with a button.
2. Display the frame.
3. When the button is clicked, create an icon of the image using class ImageIcon.
4. Add the icon to a label and then add the label to the frame.
Here is source code of the Java Program to display image in frame when button is clicked. The program is successfully compiled and tested using javac compiler on Fedora 30. The program output is also shown below.
/*Java Program to Display Image when Button is Clicked*/
import javax.swing.*;
import javax.swing.ImageIcon.*;
import java.awt.*;
import java.awt.event.*;
class Button_Image implements ActionListener
{
static JFrame frame;
//Driver function
public static void main(String args[])
{
//Create a frame
frame=new JFrame("Image on Click");
frame.setSize(500,500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setBackground(Color.white);
frame.setLayout(new FlowLayout());
//Create a button
JButton button=new JButton("Display");
frame.add(button);
//Create an object
Button_Image obj=new Button_Image();
//Associate ActionListener with button
button.addActionListener(obj);
//Display the frame
frame.setVisible(true);
}
//Function to display image
public void actionPerformed(ActionEvent e)
{
//Display Image
ImageIcon icon=new ImageIcon("logo.jpeg");
JLabel label=new JLabel(icon);
frame.add(label);
frame.pack();
frame.setSize(500,500);
}
}
1. A frame with a button is created.
2. When the button is clicked, an icon of the image is created using class ImageIcon. The file name of the image is given as a parameter. It is not required to mention the file path is the icon is in the present working directory. Otherwise, complete file path is required.
3. Add the icon to a label and add the label to the frame.
4. Resize the frame after adding the image to the frame as we are using the pack function which may change the size of frame.
Here’s the run time test cases to display an image when a button is clicked.
Test case 1 – To display the frame with the button.
Test case 2 – To display the icon in the frame.
Sanfoundry Global Education & Learning Series – Java Programs.
- Practice BCA MCQs
- Practice Programming MCQs
- Practice Information Technology MCQs
- Apply for Computer Science Internship
- Check Programming Books