Consider this class, called PetPanel: import java.awt.*; import javax.swing.*; i
ID: 3579967 • Letter: C
Question
Consider this class, called PetPanel: import java.awt.*; import javax.swing.*; import java.awt.event.*; // needed for event handling public class PetPanel extends JPanel implements ActionListener{ JButton quit = new JButton("Quit"); // make button object JButton pet = new JButton("Pet"); boolean even = true; int yPos = 10; public PetPanel(){ this.add(quit); quit.addActionListener(this); this.add(pet); } public void paintComponent(Graphics g){ super.repaint(); if (even) g.drawString("dog", 100, yPos); else g.drawString("cat", 100, yPos); } public void actionPerformed(ActionEvent e){ if (e.getSource() == quit) System.exit(0); else if (e.getSource() == pet){ even = !even; yPos = yPos + 20; repaint(); } } } When used with this driver class: public class PetDriver{ public static void main(String[] args){ DisplayWindow d = new DisplayWindow(); PetPanel s = new PetPanel(); d.addPanel(s); d.showFrame(); } }
However, there is a bug in PetPanel: the pet button doesn't work properly (although the code compiles ok). How would you fix the class so that the indicated output would be produced? You can either edit PetPanel and paste the entire class in the text area below, or you can simply explain the specific change or changes you propose
Explanation / Answer
You forgot to add actionlistener to pet button just like you did with quit button. Here is the code for that class. I have added a line in constructor of the class.
-----------------------
class PetPanel extends JPanel implements ActionListener {
JButton quit = new JButton("Quit");
// make button object
JButton pet = new JButton("Pet");
boolean even = true;
int yPos = 10;
public PetPanel() {
this.add(quit);
this.add(pet);
quit.addActionListener(this);
pet.addActionListener(this);
}
public void paintComponent(Graphics g) {
super.repaint();
if (even) {
g.drawString("dog", 100, yPos);
} else {
g.drawString("cat", 100, yPos);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == quit) {
System.exit(0);
} else if (e.getSource() == pet) {
even = !even;
yPos = yPos + 20;
repaint();
}
}
}