Java Question [Beginner Question]
Hello there. I'm supposed to create a Hangman Game for my computer class and the first step is to create the basic hangman picture (which I created). However I need to implement additional methods and I feel they're correct but they're just not working. Here it is.
Code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JFrame;
class Person extends JPanel {
private int triesLeft;
public Person ()
{
triesLeft = 6;
this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) {
if (triesLeft > 0)
showNext();
else reset();
}});}
public int getNumLeft()
{
return triesLeft;
}
public void reset()
{
triesLeft = 6;
repaint();
}
public void showNext()
{
triesLeft = triesLeft - 1;
}
public void paintComponent(Graphics g){
super.paintComponent(g);
this.setBackground(Color.YELLOW);
if (triesLeft <1)
{
g.setColor(Color.BLUE);
g.fillRect(350, 450, 60, 150);
}
if (triesLeft < 2)
{
g.setColor(new Color(190,81,215));
g.fillRect(250, 450,60,150);
}
if (triesLeft < 3)
{
g.setColor(Color.CYAN);
g.fillRect(275, 250, 120, 200);
}
if (triesLeft < 4)
{
g.setColor(new Color(176, 56, 84));
g.fillRect(215, 300, 60, 40);
}
if (triesLeft < 5)
{
g.setColor(new Color(116, 56, 34));
g.fillRect(395, 300, 60, 40);
}
if (triesLeft < 6)
{
g.setColor(new Color(11, 56, 176));
g.fillOval(300, 179, 70, 70);
}
}
public static void main(String[] args) {
JFrame j = new JFrame("Person");
j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Person p = new Person();
j.add(p);
j.setSize(800,800);
j.setVisible(true);
}
}
*I don't get any kind of error, it just shows my yellow background but when I click nothing shows up, did I implement the Mouse Listener incorrectly? Can anyone help?
Thanks!
Re: Java Question [Beginner Question]
That mouse listener looks awful. I mean really awful.
Will you rewrite it following some sane formatting conventions if I tell you what you forgot? Good. You forgot to repaint() after next(). Or next() could repaint(), like reset() does.
Re: Java Question [Beginner Question]
Hey pbrockway2 thanks for your help.
I did added the repaint () to the showNext method and it is working now. As for the mouse listener I don't really know how to make it look better, I began to program about a week ago so...sorry for the 'awful' looking code.
Re: Java Question [Beginner Question]
Read the first sentence of the API doc for the MouseAdapter API doc.
Listeners consist of one or more methods that will be called when a specific event occurs.
What specific events are your listener methods coded to handle?