It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm learning about double buffering and the book I got from my teacher tells me to write what I have written. But when java tries to get the graphics object from the image it crashes.
frame = Image
engine = Graphics
Error
Exception in thread "main" java.lang.NullPointerException
at Engine.<init>(Engine.java:30)
at Game.<init>(Game.java:35)
at Game.main(Game.java:22)
Game.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.*;
import java.util.Timer;
public class Game implements ActionListener {
private static Game hosmos2;
private JFrame frmMain;
private AntiCheat holyanticheat;
private Dimension screen;
private Engine holyengine;
private int sx, sy;
private Timer timCheat;
public static void main(String[] args) throws FileNotFoundException, InterruptedException {
hosmos2 = new Game();
}
private Game() throws FileNotFoundException, InterruptedException {
frmMain = new JFrame("Hosmos 2");
frmMain.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmMain.setSize(1366, 768);
screen = Toolkit.getDefaultToolkit().getScreenSize();
sx = (int) ((screen.getWidth() - frmMain.getWidth()) / 2);
sy = (int) ((screen.getHeight() - frmMain.getHeight()) / 2);
frmMain.setLocation(sx, sy);
holyanticheat = new AntiCheat();
holyengine = new Engine();
timCheat = new Timer();
frmMain.setVisible(true);
timCheat.schedule(holyanticheat, 500);
Thread.sleep(1000);
timCheat.cancel();
}
public void actionPerformed(ActionEvent e) {
}
}
Engine.java
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.*;
public class Engine extends JPanel {
private boolean countdown, quality;
private Font text, text2;
private Graphics engine;
private Image frame;
private ImageIcon background, button1, button21, button22, button3, button4, button51, button52, header;
private int weedbackground, fps, fps2;
public Rectangle box1, box2, box3, box4, box5;
public static void main(String[] args) {
}
public Engine() {
this.setBackground(Color.black);
frame = createImage(getSize().width, getSize().height);
text = new Font("Microsoft Sans Serif", Font.BOLD, 24);
text2 = new Font("Microsoft Sans Serif", Font.BOLD, 8);
engine = frame.getGraphics(); // Error
background = new ImageIcon("textures/background.png");
//background = background.GetThumbnailImage(source.ClientSize.Width, source.ClientSize.Height, null, IntPtr.Zero);
button1 = new ImageIcon("textures/button 1.png");
button21 = new ImageIcon("textures/button 2-1.png");
button22 = new ImageIcon("textures/button 2-2.png");
button3 = new ImageIcon("textures/button 3.png");
button4 = new ImageIcon("textures/button 4.png");
button51 = new ImageIcon("textures/button 5-1.png");
button52 = new ImageIcon("textures/button 5-2.png");
header = new ImageIcon("textures/header.png");
box1 = new Rectangle(20, 20, 87, 37);
box2 = new Rectangle(20, 60, 96, 37);
box3 = new Rectangle(20, 103, 182, 43);
box4 = new Rectangle(20, 146, 83, 43);
box5 = new Rectangle(20, 189, 206, 43);
}
public Rectangle GetBox1() {
return box1;
}
public Rectangle GetBox2() {
return box2;
}
public Rectangle GetBox3() {
return box3;
}
public Rectangle GetBox4() {
return box4;
}
public Rectangle GetBox5() {
return box5;
}
public void FPS()
{
fps2 = fps;
fps = 0;
}
public void Quality(boolean quality2)
{
quality = quality2;
}
public void Render(boolean music, boolean effect, int time, int spawned, int points, int cracktime, int crackend, int shieldtime, int shieldend, int weedtime, int weedend, ImageIcon malcolm, int malcolmX, int malcolmY, int item, ImageIcon crack, int crackX, int crackY, ImageIcon nuke, int nukeX, int nukeY, ImageIcon shield, int shieldX, int shieldY, ImageIcon skull, int skullX, int skullY, ImageIcon trollface, int trollfaceX, int trollfaceY, ImageIcon weed, int weedX, int weedY, LinkedList<Hosmin> hosmins) {
engine = frame.getGraphics();
super.paintComponent(engine);
if (effect == false) {
if (quality == false) {
background.paintIcon(this, engine, 0, 0);
}
else {
this.setBackground(Color.black);
}
}
else {
if (weedbackground == 1) {
this.setBackground(Color.green);
weedbackground++;
}
else if (weedbackground == 2) {
this.setBackground(Color.yellow);
weedbackground++;
}
else if (weedbackground == 3) {
this.setBackground(Color.red);
weedbackground = 1;
}
}
header.paintIcon(this, engine, 547, 10);
button1.paintIcon(this, engine, 20, 20);
if (music == false) {
button21.paintIcon(this, engine, 20, 60);
}
else {
button22.paintIcon(this, engine, 20, 60);
}
button3.paintIcon(this, engine, 20, 103);
button4.paintIcon(this, engine, 20, 146);
if (quality == false) {
button51.paintIcon(this, engine, 20, 189);
}
else {
button52.paintIcon(this, engine, 20, 189);
}
engine.setFont(text2);
engine.setColor(Color.green);
engine.drawString("FPS: " + fps2, 1293, 9);
engine.setFont(text);
engine.setColor(Color.red);
engine.drawString("Time: " + time, 1178, 22);
engine.drawString("Hosmins: " + spawned, 1124, 59);
engine.drawString("Points: " + points, 1160, 96);
engine.setFont(text2);
engine.setColor(Color.green);
engine.drawString("Developer: HolyDuFF", 1229, 708);
malcolm.paintIcon(this, engine, malcolmX, malcolmY);
if (countdown == true) {
if (crackend - cracktime == 0) {
countdown = false;
}
else if (cracktime >= 0) {
engine.setFont(text);
engine.setColor(Color.red);
crackend = crackend - cracktime;
if (crackend != 10) {
engine.drawString("" + crackend, malcolmX + 17, malcolmY - 40);
}
else {
engine.drawString("" + crackend, malcolmX + 7, malcolmY - 40);
}
}
else if (shieldtime >= 0) {
engine.setFont(text);
engine.setColor(Color.red);
shieldend = shieldend - shieldtime;
if (shieldend != 10) {
engine.drawString("" + shieldend, malcolmX + 17, malcolmY - 40);
}
else {
engine.drawString("" + shieldend, malcolmX + 7, malcolmY - 40);
}
}
else if (weedtime >= 0) {
engine.setFont(text);
engine.setColor(Color.blue);
weedend = weedend - weedtime;
if (weedend != 10) {
engine.drawString("" + weedend, malcolmX + 17, malcolmY - 40);
}
else {
engine.drawString("" + weedend, malcolmX + 7, malcolmY - 40);
}
}
}
for (int i = 0; i < hosmins.size(); i++) {
Hosmin temp = hosmins.get(i);
temp.Draw().paintIcon(this, engine, temp.GetX(), temp.GetY());
}
if (item == 1) {
crack.paintIcon(this, engine, crackX, crackY);
}
else if (item == 2) {
nuke.paintIcon(this, engine, nukeX, nukeY);
}
else if (item == 3) {
shield.paintIcon(this, engine, shieldX, shieldY);
}
else if (item == 4) {
skull.paintIcon(this, engine, skullX, skullY);
}
else if (item == 5) {
trollface.paintIcon(this, engine, trollfaceX, trollfaceY);
}
else if (item == 6) {
weed.paintIcon(this, engine, weedX, weedY);
}
engine.dispose();
repaint();
fps++;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(frame, 0, 0, this);
}
public void SetBackground(int background2) {
weedbackground = background2;
}
public void SetCountdown(boolean countdown2) {
countdown = countdown2;
}
public void SetBox2(int mode) {
if (mode == 1) {
box2.width = 96;
box2.height = 37;
}
else {
box2.width = 76;
box2.height = 43;
}
}
public void SetBox5(int mode) {
if (mode == 1) {
box5.width = 206;
}
else {
box5.width = 213;
}
}
}
You're calling getGraphics() on a null Image variable. If you look at the API for Component's createImage() you'll see why this is so:
returns an off-screen drawable image, which can be used for double buffering. The return value may be null if the component is not displayable. This will always happen if GraphicsEnvironment.isHeadless() returns true.
Engine is not displayed yet in its constructor. The GUI must be rendered first by calling pack() or setVisible(true) on the top level window before this JPanel will be displayed.
Related
I want to make an imitative hack System. There will be 3 windows displayed on screen. Each window will show some string Constantly (like some movie scene) . However only the third (the last) window works. So how to make every window show string at the same time?
the frame class as follow:
import java.awt.*;
import java.awt.event.*;
class sys extends Thread {
private static Frame frm;
private static TextArea txa;
private int fsx, fsy, flx, fly, tsx, tsy, tlx, tly;
private String strarr[] = new String[7];
private String frmName;
public sys(String str, String SAEC[]) {
frmName = str;
strarr = SAEC;
}
public void SettingFRM(int sx, int sy, int lx, int ly) {
//frame's location and size
fsx = sx;
fsy = sy;
flx = lx;
fly = ly;
}
public void SettingTXA(int sx, int sy, int lx, int ly) {
//textArea's location and size
tsx = sx;
tsy = sy;
tlx = lx;
tly = ly;
}
public void run() {
frm = new Frame(frmName);
//the exterior design
txa = new TextArea("", 100, 100, TextArea.SCROLLBARS_BOTH);
txa.setBounds(tlx, tly, tsx, tsy);
txa.setBackground(Color.darkGray);
txa.setFont(new Font("Arial", Font.PLAIN, 16));
txa.setForeground(Color.green);
frm.setLayout(null);
frm.setSize(fsx, fsy);
frm.setLocation(flx, fly);
frm.setVisible(true);
frm.setBackground(Color.darkGray);
frm.add(txa);
while (1 != 0) {
txa.append(strarr[(int) (Math.random() * 7)]);// to obtain new string
frm.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
try {
sleep(200);
} catch (InterruptedException e) {
}
}
}
}
main program as follow:
public class ImitativeHackSystem {
public static void main(String[] args) throws InterruptedException {
//specific string
String strarr[] = new String[9];
strarr[0] = new String("Hacking... Time estimate 25 seconds...\n");
strarr[1] = new String("Retrying...\n");
strarr[2] = new String("Error! Code:e2130443523\n");
strarr[3] = new String("Success! IP:192.168.0.1\n");
strarr[4] = new String("picking datas...\n");
strarr[5] = new String("Anti-system started\n");
strarr[6] = new String("Has been discovering... fake random IP address\n");
strarr[7] = new String("01011010000011001000000011111101010");
strarr[8] = new String("111101010101001101101101010011010");
//object array
sys fhs[] = new sys[3];
for (int i = 0; i < 3; i++)
fhs[i] = new sys("Fake Hacking System", strarr);
fhs[0].SettingTXA(635, 690, 5, 30);
fhs[0].SettingFRM(640, 720, 0, 0);
fhs[1].SettingTXA(635, 330, 5, 30);
fhs[1].SettingFRM(640, 360, 645, 0);
fhs[2].SettingTXA(635, 330, 5, 30);
fhs[2].SettingFRM(640, 360, 645, 365);
//to execute
for (int i = 0; i < 3; i++) {
fhs[i].start();
Thread.sleep(500);
}
}
}
I have made a reset button which doesn't take away the focus of the KeyListener so that the game could still be playable after the clicking of the button. The rest of the button is all about resetting locations, emptying arraylists and arrays and so on. But it seems like whenever I click the restart button, the player object does go to its starting point, x = 2 y = 0. But after that whenever I make a move I see the man object/picture move to the position in was in before so the restart button isn't working at all. The player object is actually still at the location in which it stood when the restart button was clicked. I have read that there might be a second panel added beneath and thus the real panel not changing? I'm not sure and require your help.
My question specific: Why does the reset button not suffice for the changing of the player/man objects location, why is it failing?
package riddle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GameFrame extends JFrame {
private JPanel p2;
private JButton reset;
private GameDraw component;
private Man m;
public GameFrame() {
this.setTitle("Riddle Man");
this.setSize(719, 850);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
component = new GameDraw();
m = new Man(component);
component.addKeyListener(m);
component.requestFocus();
createButton();
createPanel();
}
private void createButton() {
reset = new JButton("Restart");
ActionListener listener = new ClickListener();
reset.addActionListener(listener);
}
private void createPanel() {
p2 = new JPanel();
p2.setLayout(null);
component.setBounds(0, 0, 800, 800);
reset.setBounds(0, 725, 100, 50);
p2.add(component);
p2.add(reset);
add(p2);
}
class ClickListener implements ActionListener {
public ClickListener(){
}
#Override
public void actionPerformed(ActionEvent e) {
reset.setFocusable(false);
component.resetGame();
}
}
}
package riddle;
import org.apache.commons.lang3.StringUtils;
import java.awt.Color;
import static java.awt.Frame.NORMAL;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
public class GameField {
public String[][] field;
private String grass, wall, note, end, theRiddle, theAnswer;
private ArrayList<Integer> arrayG;
private ArrayList<Integer> arrayW;
private ArrayList<Integer> arrayN;
private ArrayList<Integer> arrayE;
private Riddle riddle;
private int instantRight, count, wrongs, retries;
private boolean ok = false;
public GameField() {
field = new String[10][10];
grass = "Grass";
wall = "Wall";
note = "Note";
end = "End";
theRiddle = "";
theAnswer = "";
instantRight = 0;
count = 0;
wrongs = 0;
retries = 0;
arrayG = new ArrayList<Integer>(Arrays.asList(0, 9, 10, 19, 20, 29, 30, 39, 40, 49, 50, 59, 60, 69, 70, 79, 80, 89, 90, 99));
arrayW = new ArrayList<Integer>(Arrays.asList(1, 3, 4, 5, 6, 7, 8, 11, 18, 21, 22, 23, 24, 25, 26, 28, 31, 38, 41, 43, 44, 45, 46, 47, 48, 51, 58, 61, 62, 63, 64, 65, 66, 68, 71, 78, 81, 83, 84, 85, 86, 87, 88, 91, 98));
arrayN = new ArrayList<Integer>(Arrays.asList(17, 35, 32, 54, 57, 76, 72, 94));
arrayE = new ArrayList<Integer>(Arrays.asList(97));
riddle = new Riddle();
fillField();
}
public String checkField(int x, int y) {
String result = "";
if (field[y][x] == "Wall") {
result = wall;
} else if (field[y][x] == "Note") {
result = note;
} else if (field[y][x] == "End") {
result = end;
endGame();
}
return result;
}
private void fillField() {
int k = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
if (arrayG.contains(k)) {
field[i][j] = grass;
} else if (arrayW.contains(k)) {
field[i][j] = wall;
} else if (arrayN.contains(k)) {
field[i][j] = note;
} else if (arrayE.contains(k)) {
field[i][j] = end;
}
k++;
}
}
}
public void setField(int x, int y) {
field[x][y] = null;
}
public boolean riddleTime() {
boolean check = false;
theRiddle = riddle.generateRiddle();
theAnswer = riddle.getAnswer();
while (!check) {
check = checkReply(theRiddle, theAnswer);
}
return check;
}
public boolean checkReply(String question, String answer) {
ImageIcon image = new ImageIcon(this.getClass().getResource("/resources/bad.png"));
ImageIcon image2 = new ImageIcon(this.getClass().getResource("/resources/good.png"));
String[] option = {"Yes", "Quit"};
String reply = JOptionPane.showInputDialog(question);
if (reply.contains(answer.toLowerCase()) || reply.contains(StringUtils.capitalize(answer)) || reply.contains(answer.toUpperCase())) {
JOptionPane.showMessageDialog(null, riddle.getResponseC(), "", NORMAL, image2);
ok = true;
if (count == 0) {
instantRight++;
} else {
count = 0;
}
} else {
wrongs++;
int selectedValue = JOptionPane.showOptionDialog(null, riddle.getResponseW(), "", JOptionPane.YES_NO_OPTION, JOptionPane.YES_NO_OPTION, image, option, NORMAL);
if (selectedValue == JOptionPane.YES_OPTION) {
checkReply(question, answer);
retries++;
}
if (selectedValue == JOptionPane.NO_OPTION) {
System.exit(0);
}
count++;
}
return ok;
}
private void endGame() {
ImageIcon bad = new ImageIcon(this.getClass().getResource("/resources/endingbad.png"));
ImageIcon good = new ImageIcon(this.getClass().getResource("/resources/endinggood.png"));
ImageIcon info = new ImageIcon(this.getClass().getResource("/resources/info.png"));
if (instantRight >= 6) {
JOptionPane.showMessageDialog(null, "", "", NORMAL, good);
JOptionPane.showMessageDialog(null, "<html><center><br><br>Instant Rights: " + instantRight + "\n" + "\n" + "Wrongs: " + wrongs + "\n" + "\n" + "Retries: " + retries + "\n" + "\n" + " Wisdom Level: " + indicate(instantRight, wrongs, retries), " Statistics", NORMAL, info);
} else {
JOptionPane.showMessageDialog(null, "", "", NORMAL, bad);
JOptionPane.showMessageDialog(null, "\n" + "Instant Rights: " + instantRight + "\n" + "\n" + "Wrongs: " + wrongs + "\n" + "\n" + "Retries: " + retries + "\n" + "\n" + " Wisdom Level: " + indicate(instantRight, wrongs, retries), " Statistics", NORMAL, info);
}
}
public String indicate(int instantRight, int wrongs, int retries) {
String level = "";
if (instantRight >= 6 && wrongs <= 4 && retries <= 4) {
level = "HIGH";
} else if (instantRight <= 3 && wrongs > 6 && retries > 6) {
level = "LOW";
} else {
level = "AVERAGE";
}
return level;
}
public void resetGame(){
fillField();
riddle.resetGame();
instantRight = 0;
wrongs = 0;
retries = 0;
count = 0;
}
}
package riddle;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JComponent;
public class GameDraw extends JComponent {
private int rows;
private int columns;
private int RWIDTH;
private int RHEIGHT;
private int manX;
private int manY;
private BufferedImage man, grass, wall, note, end;
private Man m;
private GameField f;
public GameDraw() {
//Integer variables
rows = 9;
columns = 9;
RWIDTH = 70;
RHEIGHT = 70;
manX = 2;
manY = 0;
f = new GameField();
m = new Man(this);
this.setFocusable(true);
URL resourceMan = this.getClass().getResource("/resources/man.png");
try {
man = ImageIO.read(resourceMan);
} catch (IOException e) {
System.out.println("Er ging iets mis met het laden van de afbeelding van de speler");
}
}
#Override
public void paintComponent(Graphics g) {
drawField(g);
drawMan(g);
drawObjects(g);
}
private void drawField(Graphics g) {
int x = 0;
int y = 0;
Color lightgray = new Color(192, 192, 192);
for (int i = 0; i < rows + 1; i++) {
for (int j = 0; j < columns; j++) {
g.setColor(lightgray);
g.fillRect(x, y, RWIDTH, RHEIGHT);
x += RWIDTH;
}
g.setColor(lightgray);
g.fillRect(x, y, RWIDTH, RHEIGHT);
x = 0;
y += RHEIGHT;
}
}
private void drawMan(Graphics g) {
g.drawImage(man, manX * RWIDTH, manY * RHEIGHT, RWIDTH, RHEIGHT, this);
}
public void moveMan(int x, int y) {
manX = x;
manY = y;
repaint();
System.out.println(manX + " " + manY);
}
private void drawObjects(Graphics g) {
URL resourceGrass = this.getClass().getResource("/resources/Grassy.png");
URL resourceWall = this.getClass().getResource("/resources/wall.png");
URL resourceNote = this.getClass().getResource("/resources/note.png");
URL resourceEnd = this.getClass().getResource("/resources/chest.png");
//Grass object
try {
grass = ImageIO.read(resourceGrass);
wall = ImageIO.read(resourceWall);
note = ImageIO.read(resourceNote);
end = ImageIO.read(resourceEnd);
} catch (IOException e) {
System.out.println("Er ging iets mis met het laden van de afbeelding van de speler");
}
for (int j = 0; j < rows + 1; j++) {
for (int i = 0; i < columns + 1; i++) {
if (f.field[i][j] == "Grass") {
g.drawImage(grass, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
if (f.field[i][j] == "Wall") {
g.drawImage(wall, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
if (f.field[i][j] == "Note") {
g.drawImage(note, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
if (f.field[i][j] == "End") {
g.drawImage(end, j * RWIDTH, i * RHEIGHT, RWIDTH, RHEIGHT, this);
}
}
}
}
public void repaintField(int x, int y) {
f.field[x][y] = null;
repaint();
}
public void resetGame(){
f.resetGame();
m.resetGame();
System.out.println(manX + " " + manY);
}
}
package riddle;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class Man implements KeyListener {
private int locationX;
private int locationY;
private GameDraw draw;
private GameField field;
public Man(GameDraw draw) {
locationX = 2;
locationY = 0;
this.draw = draw;
field = new GameField();
}
#Override
public void keyTyped(KeyEvent e) {
}
#Override
public void keyPressed(KeyEvent e) {
int key = e.getKeyCode();
String check;
boolean pass;
switch (key) {
case KeyEvent.VK_UP:
locationY--;
if (locationY < 0) {
locationY++;
}
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
} else if (check.equals("Wall") || check.equals("End")) {
locationY++;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationY++;
}
}
break;
case KeyEvent.VK_DOWN:
locationY++;
if (locationY > 9) {
locationY--;
}
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
}
if (check.equals("Wall") || check.equals("End")) {
locationY--;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationY--;
}
}
break;
case KeyEvent.VK_LEFT:
locationX--;
;
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
}
if (check.equals("Wall") || check.equals("End")) {
locationX++;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationX++;
}
}
break;
case KeyEvent.VK_RIGHT:
System.out.println(locationX + " " + locationY);
locationX++;
check = field.checkField(locationX, locationY);
if (!"Wall".equals(check) && !"Note".equals(check) && !"End".equals(check)) {
draw.moveMan(locationX, locationY);
}
if (check.equals("Wall") || check.equals("End")) {
locationX--;
} else if (check.equals("Note")) {
pass = field.riddleTime();
if (pass) {
clearNote(locationX, locationY);
draw.moveMan(locationX, locationY);
} else {
locationX--;
}
}
break;
default:
break;
}
}
#Override
public void keyReleased(KeyEvent e) {
}
public void clearNote(int x, int y) {
field.setField(y, x);
draw.repaintField(y, x);
}
public void resetGame(){
locationX = 2;
locationY = 0;
draw.moveMan(locationX, locationY);
System.out.println(locationX + " " + locationY);
}
}
package riddle;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Riddle {
private ArrayList<String> riddles;
private ArrayList<String> answers;
private ArrayList<String> correct;
private ArrayList<String> wrong;
private ArrayList<Integer> used;
private ArrayList<Integer> used2;
private Random ran;
private int indexAnswer;
public Riddle() {
riddles = new ArrayList<String>();
answers = new ArrayList<String>();
correct = new ArrayList<String>();
wrong = new ArrayList<String>();
used = new ArrayList<Integer>();
used2 = new ArrayList<Integer>();
ran = new Random();
fillRiddles();
fillAnswers();
fillCorrect();
fillWrong();
}
private void fillRiddles() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\riddles.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
riddles.add(s);
}
}
}
private void fillAnswers() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\answers.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
answers.add(s);
}
}
}
private void fillCorrect() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\correct.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
correct.add(s);
}
}
}
private void fillWrong() {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("C:\\Users\\John\\Documents\\NetBeansProjects\\Riddle\\src\\resources\\wrong.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (s2.hasNext()) {
String s = s2.nextLine();
wrong.add(s);
}
}
}
public String generateRiddle() {
String theRiddle = "";
int index = ran.nextInt(riddles.size());
if (!used.contains(index)) {
theRiddle = riddles.get(index);
indexAnswer = index;
used.add(index);
} else {
theRiddle = generateRiddle();
}
return theRiddle;
}
public String getAnswer() {
String theAnswer = answers.get(indexAnswer);
return theAnswer;
}
public String getResponseC() {
String response = "";
int index = ran.nextInt(correct.size());
if (!used2.contains(index)) {
response = correct.get(index);
used2.add(index);
} else {
response = getResponseC();
}
return response;
}
public String getResponseW() {
String response = "";
int index = ran.nextInt(wrong.size());
response = wrong.get(index);
return response;
}
public void resetGame(){
riddles.clear();
answers.clear();
wrong.clear();
correct.clear();
used.clear();
used2.clear();
fillRiddles();
fillAnswers();
fillCorrect();
fillWrong();
indexAnswer = 0;
}
}
I'm making a game similar to feeding frenzy. I'm using mouseMotionListener to move a JLabel around a JFrame. At the same time, there are other JLabels that act as other fish to be eaten by the JLabel controlled by the mouse. Every time a JLabel fish (not controlled by mouse) moves in to and out of the screen, the JLabel controlled by the mouse returns back to a standard location on the screen, the center of the top half of the screen. What can I do to stop that from occurring?
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import sun.audio.*;
import java.io.*;
import java.util.Timer;
import java.util.TimerTask;
import java.awt.event.MouseEvent;
public class playFishGame extends JPanel implements MouseMotionListener {
private JFrame board;// the main board
private JLabel fish;
private JLabel enemyFishS;
private JLabel enemyFishS2;
private JLabel enemyFishS3;
private ImageIcon fishPic;
private ImageIcon enemyFishSPic;
private ImageIcon winBackground;
private ImageIcon background;
private ImageIcon loseBackground;
ImageIcon fishSmall1r = new ImageIcon("data/fishSmall1r.png");
ImageIcon fishSmall1l = new ImageIcon("data/fishSmall1l.png");
ImageIcon fishSmall2r = new ImageIcon("data/fishSmall2r.png");
ImageIcon fishSmall2l = new ImageIcon("data/fishSmall2l.png");
ImageIcon fishSmall4r = new ImageIcon("data/fishSmall4r.png");
ImageIcon fishSmall4l = new ImageIcon("data/fishSmall4l.png");
private fish fishFish;
private fish enemyFishSFish;
private fish enemyFishSFish2;
private fish enemyFishSFish3;
private int origin;
private boolean contact, win;
Cursor blankCursor = null;
public static void main(String args[]) {
playFishGame play = new playFishGame();
}
public playFishGame() {
blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
Toolkit.getDefaultToolkit().createImage("data/blank.png"),
new Point(0, 0), "blankCursor"); // blank.png is any tranparent
// image.
board = new JFrame("Play Fish Game");
board.setSize(1300, 700);
board.getContentPane().setCursor(blankCursor);
board.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
board.add(this);// adds JLabel to JFrame
this.addMouseMotionListener(this);
board.setVisible(true);
ImageIcon fishPic = new ImageIcon("data/sfr.gif");
fish = new JLabel(fishPic);
enemyFishS = new JLabel(" ");
enemyFishS2 = new JLabel(" ");
fishFish = new fish(617, 0);
enemyFishSFish = new fish(1300, 350);
enemyFishSFish2 = new fish(0, 500);
// enemyFishSFish3= new fish(1300,200);
this.add(fish);
this.add(enemyFishS);
this.add(enemyFishS2);
contact = false;
win = false;
repaint();
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (enemyFishSFish.initiate == true) {
randomFishSmall(enemyFishSFish, enemyFishS);// picks image and
// starting
// point/side
enemyFishSFish.initiate = false;
}
if (enemyFishSFish.chooseSide == 0) {
enemyFishSFish.moveLeft();
if (enemyFishSFish.getX() < 5) {
enemyFishSFish.initiate = true;
}
} else if (enemyFishSFish.chooseSide == 1) {
enemyFishSFish.moveRight();
if (enemyFishSFish.getX() > 1295) {
enemyFishSFish.initiate = true;
}
}
if (enemyFishSFish2.initiate == true) {
randomFishSmall(enemyFishSFish2, enemyFishS2);// picks image and
// starting
// point/side
enemyFishSFish2.initiate = false;
}
if (enemyFishSFish2.chooseSide == 0) {
enemyFishSFish2.moveLeft();
if (enemyFishSFish2.getX() < 5) {
enemyFishSFish2.initiate = true;
}
} else if (enemyFishSFish2.chooseSide == 1) {
enemyFishSFish2.moveRight();
if (enemyFishSFish2.getX() > 1295) {
enemyFishSFish2.initiate = true;
}
}
enemyFishS.setLocation(enemyFishSFish.getX(), enemyFishSFish.getY());
contact(enemyFishSFish);
enemyFishS2.setLocation(enemyFishSFish2.getX(),
enemyFishSFish2.getY());
contact(enemyFishSFish2);
// contact(enemyFishSFish);
// enemyFishS2.setLocation(enemyFishSFish2.getX(),enemyFishSFish2.getY());
// enemyFishS3.setLocation(enemyFishSFish3.getX(),enemyFishSFish3.getY());
}
}, 0, 100);
board.setState(Frame.ICONIFIED);
board.setState(Frame.NORMAL);
}
public void mouseMoved(MouseEvent evt) {
System.out.println(evt.getPoint().x + ", " + evt.getPoint().y);
if ((evt.getPoint().x < 1231) && (evt.getPoint().y < 623)) {
fish.setLocation(evt.getPoint().x, evt.getPoint().y);
fishFish.override(evt.getPoint().x, evt.getPoint().y);
}
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
origin = fishFish.getX();
}
}, 0, 100);
int posneg = origin - evt.getPoint().x;
ImageIcon sfr = new ImageIcon("data/sfr.gif");
ImageIcon sfl = new ImageIcon("data/sfl.gif");
ImageIcon mfr = new ImageIcon("data/mfr.gif");
ImageIcon mfl = new ImageIcon("data/mfl.gif");
if (posneg < 0) {
if (fishFish.sFish < 10)
fish.setIcon(sfr);
if (fishFish.sFish > 9)
fish.setIcon(mfr);
}
if (posneg > 0) {
if (fishFish.sFish < 10)
fish.setIcon(sfl);
if (fishFish.sFish > 9)
fish.setIcon(mfl);
}
}
public void mouseDragged(MouseEvent evt) {
}
// 95/34
public void contact(fish enemyFish) {
if ((Math.abs(fishFish.getX() - enemyFish.getX())) < 48
&& (Math.abs(fishFish.getY() - enemyFish.getY()) < 36)
&& (fishFish.sFish < 10)) {
fishFish.sFish++;
enemyFish.initiate = true;
}
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
background = new ImageIcon("data/background3.png");
winBackground = new ImageIcon("data/");
loseBackground = new ImageIcon("data/");
if ((contact == false) && (win == false))
g.drawImage(background.getImage(), 0, 0, null);
if (contact == true)
g.drawImage(loseBackground.getImage(), 0, 0, null);
if (win == true)
g.drawImage(winBackground.getImage(), 0, 0, null);
}
public void randomFishSmall(fish changeFishFish, JLabel changeFish) {
int chooseType = (int) (Math.random() * 3);
// int chooseType=2;
int chooseSide = (int) (Math.random() * 2);// left=0right=1
int chooseSpeed = (int) (Math.random() * 12) + 6;
int choosePlacement = (int) (Math.random() * 1288) + 15;
changeFishFish.chooseType = chooseType;
changeFishFish.chooseSide = chooseSide;
changeFishFish.chooseSpeed = chooseSpeed;
changeFishFish.choosePlacement = choosePlacement;
if (chooseType == 0) {
if (chooseSide == 0) {
changeFish.setIcon(fishSmall1l);
changeFishFish.override(1300, choosePlacement);
// changeFishFish.
} else {
changeFish.setIcon(fishSmall1r);
changeFishFish.override(0, choosePlacement);
}
changeFish.setLocation(changeFishFish.getX(), changeFishFish.getY());
} else if (chooseType == 1) {
if (chooseSide == 0) {
changeFish.setIcon(fishSmall2l);
changeFishFish.override(1300, choosePlacement);
} else {
changeFish.setIcon(fishSmall2r);
changeFishFish.override(0, choosePlacement);
}
changeFish.setLocation(changeFishFish.getX(), changeFishFish.getY());
} else if (chooseType == 2) {
if (chooseSide == 0) {
changeFish.setIcon(fishSmall4l);
changeFishFish.override(1300, choosePlacement);
// changeFishFish.
} else {
changeFish.setIcon(fishSmall4r);
changeFishFish.override(0, choosePlacement);
}
changeFish.setLocation(changeFishFish.getX(), changeFishFish.getY());
}
}
}
First of all:
Class names start with an upper case character. Learn by example. Just look at the Java API and you will see all class names start with an upper case character.
Don't do I/O in a painting method. Painting methods are called whenever Swing determines a component needs to be repainted. It is not efficient to read files every time. Read the images when the class is created.
Don't hardcode the size of the frame - board.setSize(1300, 700); Not everybody uses the same resolution. To maximize the frame you can use: board.setExtendedState(JFrame.MAXIMIZED_BOTH);
returns back to a standard location on the screen, the center of the top half of the screen
By default a JPanel uses a FlowLayout. When you change the location of the other labels the layout manager is invoked to components a place in the position determined by the layout manager.
If you have random placement of a component because you are using the mouse to drag the component, then you need to use a "null layout" on the panel. When you do this you are now responsible for manually setting the "size and location" of every component you add to the panel.
i have this class,on which i noticed if i use setFont(...) it 'll slow down the execution of the entire program.
public class MenuState extends GameState {
private String[] options = { "Start ", "Options","Quit"};
private int currentSelection;
private Font font;
protected MenuState(GameStateManager gameStateManager) {
super(gameStateManager);
init();
}
public void init() {
currentSelection = 0;
font = new Font("Times New Roman", Font.BOLD, 30);
}
public void update() {
}
public void render(Graphics graphic) {
for (int i = 0; i < options.length; i++) {
if (i == currentSelection) {
graphic.setColor(Color.GREEN);
} else {
graphic.setColor(Color.BLACK);
}
if (i == 0) {
graphic.setFont(font);
graphic.drawString(options[i],
GuiDimension.WIDTH.getValue() / 2 - 47, 500);
}
if (i == 1) {
graphic.setFont(font);
graphic.drawString(options[i],
GuiDimension.WIDTH.getValue() / 2 - 107, 550);
}
if (i == 2) {
graphic.setFont(font);
graphic.drawString(options[i],
GuiDimension.WIDTH.getValue() / 2 - 47, 600);
}
}
}
now if if I comment this row:
graphic.setFont(font);
the execution is normal otherwise it is slow.
someone can tell me the reason?
I'm banging my head against the wall and have a feeling that I'm going about this completely incorrectly. I'm creating a simple hangman game and cannot, for the life of me, get the result of my paintComponent() method to display with the buttons I've created using a JFrame.
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
import javax.swing.*;
public class hangman extends JPanel implements ActionListener {
public static final int youLose=6;
public int wrongGuess;
public String message;
public String theWord;
public StringBuffer guessWord;
public JButton restartButton;
public JButton playButton;
public JTextArea userInput;
public static void main(String[] args) {
hangman h = new hangman();
h.initialize();
}
public void initialize() {
userInput = new JTextArea();
restartButton = new JButton("Restart");
playButton = new JButton("Play");
JFrame frame = new JFrame("Hangman");
frame.setVisible(true);
frame.setLayout(new GridLayout(1,4));
frame.setBounds(0, 0, 500, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.add(restartButton);
frame.add(playButton);
frame.add(new JLabel("Enter guess: "));
frame.add(userInput);
restartButton.addActionListener(this);
playButton.addActionListener(this);
startGame();
}
public void paintComponent(Graphics g) {
//(left, top, right, bottom)
g.drawLine(90, 250,200,250);
g.drawLine(125,250,125,150);
g.drawLine(125,150,175,150);
g.drawLine(175,150,175,175);
if (wrongGuess > 0){ //head
g.drawOval(170,175,10,12);
}
if (wrongGuess > 1){ //body
g.drawLine(175,187,175,205);
}
if (wrongGuess > 2){ //left arm
g.drawLine(163,185,173,190);
}
if (wrongGuess > 3){ //right arm
g.drawLine(177,190,187,185);
}
if (wrongGuess > 4){ //left leg
g.drawLine(168,220,173,205);
}
if (wrongGuess > 5){ //right leg
g.drawLine(177,205,182,220);
}
g.drawString( message, 40, 290 );
g.drawString( new String (guessWord), 40, 275);
}
public void actionPerformed(ActionEvent event){
if (event.getSource() == restartButton){
restart();
startGame();
}
if (event.getSource() == playButton){
analyzeGuess();
userInput.setText("");
repaint();
}
setVisible(true);
}
public void restart() {
Graphics g = getGraphics();
Dimension d = getSize();
Color c = getBackground();
g.setColor(c);
g.fillRect(0,0,d.width,d.height);
repaint();
}
public void startGame() {
wrongGuess = 0;
String[] wordArray = {"computer", "science", "java", "application", "programming", "university",
"homework", "assignment", "cactus", "flower", "button", "keyboard", "graphic", "interface",
"collegiate", "graduate", "headphones", "building", "radiator", "flora", "fauna", "suitcase",
"sweater", "television", "library", "elevator", "precidence", "ancient", "basketball", "bracket",
"alphabetical", "christmas", "hannukah"};
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(wordArray.length);
theWord = new String(wordArray[randomInt]);
char positions[] = new char[theWord.length()];
for (int i=0; i<theWord.length(); i++) {
positions[i] = '_';
}
String s = new String(positions);
guessWord = new StringBuffer(s);
userInput.setText("");
message="";
repaint();
}
private void analyzeGuess() {
String userGuess, temp;
char letter;
userGuess = userInput.getText();
letter = userGuess.charAt(0);
if (!Character.isLetter(letter)){
message="Invalid character";
return;
}
if (userGuess.length()>1){
message="Only enter one letter";
return;
}
temp = new String(guessWord);
if (temp.indexOf(userGuess) != -1){
message="Letter has already been guessed";
return;
}
if (theWord.indexOf(userGuess) == -1){
message="";
message = new String(message);
wrongGuess++;
message = "You have "+ (youLose-wrongGuess) + " guesses left.";
if (wrongGuess==youLose){
message="You lose! The word was '"+theWord+"'"+"\nClick restart to try again.";
}
return;
}
for (int i=0; i<theWord.length(); i++){
if (theWord.charAt(i) == letter){
guessWord.setCharAt(i, letter);
}
}
temp = new String(guessWord);
if (temp.indexOf('_') == -1){
message="You win!";
return;
}
message="";
repaint();
}
}
As I see it, the major problem you have is here...
public void restart() {
// May return null and is only a snapshot of what's current within the components
// graphics buffer...
Graphics g = getGraphics();
Dimension d = getSize();
Color c = getBackground();
g.setColor(c);
g.fillRect(0,0,d.width,d.height);
// Every thing you just did will not be discard as when paintComponent
// is called...
repaint();
}
You should also be called super.paintComponent as the first statement within your paintComponent method
All painting should be done in your paintComponent method.
Check out Painting in AWT and Swing for more details about the paint engine.
Working Example
Basically, your controls are hiding your custom painting.
One of the most important aspects of OO is separation of responsibility. That is, each class should do one job (and do it well).
In your case, your HangMan class was trying to manage the UI controls, custom painting and basic game rules...
The example blow separates the game rules/state into a model which is shared by the main view and the panel responsible for painting the state of the game....
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class TestHangMan01 {
public static void main(String[] args) {
new TestHangMan01();
}
public TestHangMan01() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new Hangman());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class HangManModel {
public int youLose;
public int wrongGuess;
public String message;
public String theWord;
public StringBuffer guessWord;
private Set<ChangeListener> listeners;
public HangManModel() {
listeners = new HashSet<>(25);
}
public void setTheWord(String theWord) {
this.theWord = theWord;
guessWord = new StringBuffer(theWord.length());
while (guessWord.length() < theWord.length()) {
guessWord.append("_");
}
youLose = theWord.length();
wrongGuess = 0;
message = "";
fireStateChanged();
}
public void addChangeListener(ChangeListener listener) {
listeners.add(listener);
}
public void removeChangeListener(ChangeListener listener) {
listeners.remove(listener);
}
protected void fireStateChanged() {
if (listeners.size() > 0) {
ChangeEvent evt = new ChangeEvent(this);
for (ChangeListener listener : listeners) {
listener.stateChanged(evt);
}
}
}
public int getWrongGuess() {
return wrongGuess;
}
public String getMessage() {
return message;
}
public String getGuessWord() {
return guessWord.toString();
}
public void setMessage(String value) {
if (message == null ? value != null : !message.equals(value)) {
this.message = value;
fireStateChanged();
}
}
public void guess(char letter) {
if (!Character.isLetter(letter)) {
setMessage("Invalid character");
} else {
String temp = new String(guessWord);
if (temp.indexOf(letter) != -1) {
message = "Letter has already been guessed";
} else {
if (theWord.indexOf(letter) == -1) {
wrongGuess++;
if (wrongGuess == youLose) {
setMessage("You lose! The word was '" + theWord + "'" + "\nClick restart to try again.");
} else {
setMessage("You have " + (youLose - wrongGuess) + " guesses left.");
}
} else {
for (int i = 0; i < theWord.length(); i++) {
if (theWord.charAt(i) == letter) {
guessWord.setCharAt(i, letter);
}
}
temp = new String(guessWord);
if (temp.indexOf('_') == -1) {
setMessage("You win!");
} else {
setMessage("");
}
}
}
}
}
}
public class HangManPane extends JPanel implements ChangeListener {
private HangManModel model;
public HangManModel getModel() {
return model;
}
public void setModel(HangManModel value) {
if (model != value) {
if (model != null) {
model.removeChangeListener(this);
}
this.model = value;
if (model != null) {
model.addChangeListener(this);
}
repaint();
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
HangManModel model = getModel();
//(left, top, right, bottom)
g.drawLine(90, 250, 200, 250);
g.drawLine(125, 250, 125, 150);
g.drawLine(125, 150, 175, 150);
g.drawLine(175, 150, 175, 175);
if (model.getWrongGuess() > 0) { //head
g.drawOval(170, 175, 10, 12);
}
if (model.getWrongGuess() > 1) { //body
g.drawLine(175, 187, 175, 205);
}
if (model.getWrongGuess() > 2) { //left arm
g.drawLine(163, 185, 173, 190);
}
if (model.getWrongGuess() > 3) { //right arm
g.drawLine(177, 190, 187, 185);
}
if (model.getWrongGuess() > 4) { //left leg
g.drawLine(168, 220, 173, 205);
}
if (model.getWrongGuess() > 5) { //right leg
g.drawLine(177, 205, 182, 220);
}
g.drawString(model.getMessage(), 40, 290);
g.drawString(model.getGuessWord(), 40, 275);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
public void stateChanged(ChangeEvent e) {
repaint();
}
}
public class Hangman extends JPanel implements ActionListener {
public JButton restartButton;
public JButton playButton;
public JTextField userInput;
private HangManModel model;
public Hangman() {
setModel(new HangManModel());
setLayout(new BorderLayout());
userInput = new JTextField();
restartButton = new JButton("Restart");
playButton = new JButton("Play");
JPanel controls = new JPanel(new GridLayout(1, 4));
controls.add(restartButton);
controls.add(playButton);
controls.add(new JLabel("Enter guess: "));
controls.add(userInput);
add(controls, BorderLayout.NORTH);
userInput.addActionListener(this);
restartButton.addActionListener(this);
playButton.addActionListener(this);
HangManPane hangManPane = new HangManPane();
hangManPane.setModel(getModel());
add(hangManPane);
startGame();
}
public void setModel(HangManModel model) {
this.model = model;
}
public HangManModel getModel() {
return model;
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == restartButton) {
restart();
startGame();
}
if (event.getSource() == playButton || event.getSource() == userInput) {
analyzeGuess();
userInput.setText("");
repaint();
}
setVisible(true);
}
public void restart() {
startGame();
}
public void startGame() {
String[] wordArray = {"computer", "science", "java", "application", "programming", "university",
"homework", "assignment", "cactus", "flower", "button", "keyboard", "graphic", "interface",
"collegiate", "graduate", "headphones", "building", "radiator", "flora", "fauna", "suitcase",
"sweater", "television", "library", "elevator", "precidence", "ancient", "basketball", "bracket",
"alphabetical", "christmas", "hannukah"};
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(wordArray.length);
String theWord = new String(wordArray[randomInt]);
getModel().setTheWord(theWord);
userInput.setText("");
}
private void analyzeGuess() {
String userGuess = userInput.getText();
if (userGuess.trim().length() > 0) {
getModel().guess(userGuess.charAt(0));
}
}
}
}