Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please take a look at the code below. When you click the JButton the smiley face

ID: 3767848 • Letter: P

Question

Please take a look at the code below. When you click the JButton the smiley face is supposed to change from a smiley face to a frown and then visa versa. The face is supposed to start as a smile first not a frown. Can somebody please help by making the face start as a smile first not a frown. Also there seems to be a few bugs such as every once in a while it will start as a smile but most of the time it starts as a frown. Can you please just look through the code and fix any problems that you may see. Also please check to see if I have the repaint() methods in the correct locations. Any explanations would be appreciated.

Thanks!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class JSmileFace2 extends JFrame implements ActionListener
{
JButton pressButton = new JButton("Change");
boolean smile = true;
String title = "SmileyFace";


private void smileFace(Graphics g)
{
setTitle(title);

setLayout(new FlowLayout());
add(pressButton);
pressButton.addActionListener(this);
g.setColor(Color.yellow);
g.drawArc(150, 100, 100, 200, 360, 360);
g.fillArc(100, 100, 200, 200, 360, 360);
g.setColor(Color.black);
g.drawOval(145, 150, 40, 60);
g.fillOval(145, 150, 40, 60);
g.drawOval(225, 150, 35, 60);
g.fillOval(225, 150, 35, 60);

}

@Override
public void paint(Graphics g)
{

super.paint(g);
// Added code here
if (smile)
{
drawSmile(g);
{
smile = false;
}
}

else
{
drawFrown(g);
smile = true;
}

}

private void drawSmile(Graphics g)
{
smileFace(g);
g.drawArc(155, 230, 90, 30, 180, 180);
}

private void drawFrown(Graphics g)

{
smileFace(g);
g.drawArc(155, 230, 90, 30, 0, 180);
}

@Override
public void actionPerformed(ActionEvent e)
{
repaint();
}

public static void main(String[] args)
{
JSmileFace2 smile = new JSmileFace2();
smile.setSize(400, 400);
smile.setVisible(true);
smile.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

}

Explanation / Answer

Solution:

private void smileFace(Graphics g) {
       setTitle(title);

       setLayout(new FlowLayout());
       add(pressButton);
       pressButton.addActionListener(this);
       g.setColor(Color.yellow);
       g.drawArc(150, 100, 100, 200, 360, 360);
       g.fillArc(100, 100, 200, 200, 360, 360);
       g.setColor(Color.black);
       g.drawOval(145, 150, 40, 60);
       g.fillOval(145, 150, 40, 60);
       g.drawOval(225, 150, 35, 60);
       g.fillOval(225, 150, 35, 60);
       setVisible(true); //Add this line , you got the smiley face.
   }