Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Animal Forms Exercise

Create the following view in Java and make sure that the text underneath the pictures change
according to the animal you clicked. Make sure to download the pictures from the internet and resize
them as 100 X 130.

As an example, if you click on the chinchilla, the text changes as follows:


Exercise Solution
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

public class GUIPictures extends JFrame implements ActionListener {

/*
File imageC = new File("src//images//chincilla.png");
File imageK = new File("src//images//kapibara.png");
File imageH = new File("src//images//hamster.png");
*/

ImageIcon imageC = new ImageIcon("src//images//chincilla.png");


ImageIcon imageH = new ImageIcon("src//images//hamster.png");
ImageIcon imageK = new ImageIcon("src//images//kapibara.png");

JButton btnChin = new JButton(imageC);


JButton btnHam = new JButton(imageH);
JButton btnKap = new JButton(imageK);

JLabel animalLabel = new JLabel("This is the animal you clicked");

public GUIPictures(String title) {

setTitle(title);
setSize(600,500);
setLayout(new FlowLayout());
//when the form is closed, shut down the application
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

/*if (imageC.exists())
System.out.println("Chincilla picture is found");
if (imageH.exists())
System.out.println("Hamster picture is found");
if (imageK.exists())
System.out.println("Kapibara picture is found");
*/
animalLabel.setFont(new Font("Verdana",Font.BOLD,26));

JButton myButtonsArray [] = new JButton[]


{btnChin,btnHam,btnKap};

for (JButton eachBtn : myButtonsArray){


eachBtn.setPreferredSize(new Dimension(100,130));
eachBtn.addActionListener(this);
}

add(btnChin);
add(btnKap);
add(btnHam);
add(animalLabel);
}
@Override
public void actionPerformed(ActionEvent e) {

if (e.getSource() == btnChin){
animalLabel.setText("you like chincillas!");
}
else if (e.getSource() == btnKap){
animalLabel.setText("you like kapibaras!");
}
else if (e.getSource() == btnHam){
animalLabel.setText("you like hamsters!");
}

}
}

You might also like