Saturday, April 17, 2021

Discarded idea for my point and click adventure game

 

This is the alternative version of my point and click adventure game.


I added a battle sequence but it didn't fit well with the point and click game mechanics so I discarded the idea.


I made a video about it:



and received a request for the code so here it is:

Class structure



GameManager



package Main;

import java.net.URL;
import Event.Event01;
import Event.Event02;
import Event.Event03;

public class GameManager{
		
	// MAIN CLASS
	ActionHandler aHandler = new ActionHandler(this);	// Instantiate before UI class otherwise action won't work
	public UI ui = new UI(this);
	public Player player = new Player(this);
	public SceneChanger sChanger = new SceneChanger(this);		
	Music music = new Music();
	SE se = new SE();
	public BattleManager bm = new BattleManager(this);
	
	// EVENT CLASS
	public Event01 ev1 = new Event01(this);
	public Event02 ev2 = new Event02(this);
	public Event03 ev3 = new Event03(this);
		
	// SOUND
	public URL fieldMusic  = getClass().getClassLoader().getResource("audio//bensound-acousticbreeze voldown2.wav");
	public URL fieldMusic2  = getClass().getClassLoader().getResource("audio//bensound-ofeliasdream.wav");
	public URL battleMusic  = getClass().getClassLoader().getResource("audio//bensound-epic-down.wav");
	public URL deathSound  = getClass().getClassLoader().getResource("audio//darksoulsdeath.wav");
	public URL hitSound  = getClass().getClassLoader().getResource("audio//hit.wav");
	public URL healSound  = getClass().getClassLoader().getResource("audio//healSound.wav");
	public URL guard01  = getClass().getClassLoader().getResource("audio//guard01.wav");
	public URL guard02  = getClass().getClassLoader().getResource("audio//guard02.wav");
	public URL guard03  = getClass().getClassLoader().getResource("audio//guard03.wav");
	public URL guard03b  = getClass().getClassLoader().getResource("audio//guard03b.wav");
	public URL guard04  = getClass().getClassLoader().getResource("audio//guard04.wav");
	public URL guard05  = getClass().getClassLoader().getResource("audio//guard05.wav");
	public URL guard06  = getClass().getClassLoader().getResource("audio//guard06.wav");
	public URL awesome  = getClass().getClassLoader().getResource("audio//awesome.wav");
	public URL chestopen  = getClass().getClassLoader().getResource("audio//dqchestopen.wav");
	public URL enter  = getClass().getClassLoader().getResource("audio//dqstairs.wav");
	URL currentMusic;
	

	public static void main(String[] args) {
		
		new GameManager();	
	}
	public GameManager() {
		
		// SET MUSIC
		currentMusic = fieldMusic; // Do this before showScreen1 otherwise you get NullPointer to stop the current audio
		playMusic(currentMusic);
				
		// SET SCREEN
		player.setPlayerDefaultStatus();
		sChanger.showScene1();	
		
		ui.window.setVisible(true);
	}
	public void playSE(URL url){

		se.setFile(url);
		se.play(url);
	}
	public void playMusic(URL url) {
		
		music.setFile(url);
		music.play(url);
		music.loop(url);
	}
	public void stopMusic(URL url) {
		
		music.stop(url);
	}

}


UI



package Main;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class UI {
	
	// MAIN UI
	JFrame window;
	public JTextArea messageText;	
	public JPanel bgPanel[] = new JPanel[20];
	JLabel bgLabel[] = new JLabel[20];
	public JButton choiceB1,choiceB2;
	
	// PLAYER UI
	JPanel lifePanel;
	JLabel life[] = new JLabel[6];	
	JPanel inventoryPanel;
	public JLabel sword;
	public JLabel lantern;
	public JLabel shield;
	
	// GAME OVER UI
	public JLabel titleLabel;
	public JButton restartButton;	
	
	// CLASS
	GameManager gm;
	
	public UI(GameManager gm) {
		
		this.gm = gm;
		
		createMainField();
		createPlayerField();
		createGameOverField();
		generateScreen();							
	}
	public void createMainField() {
		
		window = new JFrame("Awesome Quest III");
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		window.setLayout(null);
							
		messageText = new JTextArea();
		messageText.setBounds(50,410,700,150);
		messageText.setBackground(Color.black);
		messageText.setForeground(Color.white);
		messageText.setEditable(false);
		messageText.setLineWrap(true);
		messageText.setWrapStyleWord(true); 
		messageText.setFont(new Font("Times New Roman", Font.PLAIN, 26));
		window.add(messageText);
		choiceB1 = new JButton("Add to your wishlist");
		choiceB1.setBounds(190,320,200,50);
		choiceB1.setBackground(new Color(39,67,89));
		choiceB1.setForeground(new Color(97,195,240));
		choiceB1.setFocusPainted(false);
		choiceB1.setFont(new Font("Arial", Font.PLAIN, 17));
		choiceB1.setVisible(false);
		window.add(choiceB1);
		choiceB2 = new JButton("No way");
		choiceB2.setBounds(400,320,200,50);
		choiceB2.setBackground(new Color(39,67,89));
		choiceB2.setForeground(new Color(97,195,240));
		choiceB2.setFocusPainted(false);
		choiceB2.setFont(new Font("Arial", Font.PLAIN, 17));
		choiceB2.addActionListener(gm.aHandler);
		choiceB2.setActionCommand("noway");
		choiceB2.setVisible(false);
		window.add(choiceB2);
		
	}
	public void createBackgroundImage(int num, String bgFileName) {
		
		bgPanel[num] = new JPanel();
		bgPanel[num].setBounds(50,50,700,350);
		bgPanel[num].setBackground(Color.black);
		bgPanel[num].setLayout(null);
		bgPanel[num].setVisible(false); // So panel 2 or later panels doesn't show up at the beginning
		window.add(bgPanel[num]);
		
		bgLabel[num] = new JLabel();
		bgLabel[num].setBounds(0,0,700,350);	
		
		ImageIcon bgIcon = new ImageIcon(getClass().getClassLoader().getResource(bgFileName));
		Image image = bgIcon.getImage().getScaledInstance(700, 350, Image.SCALE_DEFAULT); // Adjust the size to the label
		bgIcon = new ImageIcon(image);
		bgLabel[num].setIcon(bgIcon);
		
//		bgPanel[num].add(bgLabel[num]);  DON'T ADD Background image to the panel yet!!!!
	}
	public void createObject(int bgNum, int objX, int objY, int objWidth, int objHeight, String objFileName, 
			String choice1Name, String choice2Name, String choice3Name, String choice1Command, String choice2Command, String choice3Command) {
		
		// CREATE POP MENU
		JPopupMenu popMenu = new JPopupMenu(); 
		
		// CREATE POP MENU ITEMS
		JMenuItem menuItem[] = new JMenuItem[4]; // Use [1], [2], [3] 				
		menuItem[1] = new JMenuItem(choice1Name);
		menuItem[1].addActionListener(gm.aHandler);
		menuItem[1].setActionCommand(choice1Command);
		popMenu.add(menuItem[1]);
		
		menuItem[2] = new JMenuItem(choice2Name);
		menuItem[2].addActionListener(gm.aHandler);
		menuItem[2].setActionCommand(choice2Command);
		popMenu.add(menuItem[2]);
		
		menuItem[3] = new JMenuItem(choice3Name);
		menuItem[3].addActionListener(gm.aHandler);
		menuItem[3].setActionCommand(choice3Command);
		popMenu.add(menuItem[3]);
		
		// CREATE OBJECTS
		JLabel objectLabel = new JLabel();
		objectLabel.setBounds(objX,objY,objWidth,objHeight);
//		objectLabel.setOpaque(true);  // Use this when you want to check where the blank object is
//		objectLabel.setBackground(Color.blue);  // Use this when you want to check where the blank object is
		
		ImageIcon objectIcon = new ImageIcon(getClass().getClassLoader().getResource(objFileName));
		Image image = objectIcon.getImage().getScaledInstance(objWidth, objHeight, Image.SCALE_DEFAULT);
		objectIcon = new ImageIcon(image);
		objectLabel.setIcon(objectIcon);
		
		objectLabel.addMouseListener(new MouseListener() {

			public void mouseClicked(MouseEvent e) {}
			public void mousePressed(MouseEvent e) {				
				if(SwingUtilities.isRightMouseButton(e)){					
					popMenu.show(objectLabel, e.getX(), e.getY());
				}	
			}
			public void mouseReleased(MouseEvent e) {}
			public void mouseEntered(MouseEvent e) {}
			public void mouseExited(MouseEvent e) {}
			
		});
		bgPanel[bgNum].add(objectLabel);						
	}
	public void createArrowButton(int bgNum, int x, int y, int width, int height, String arrowFileName, String command) {
				
		ImageIcon arrowIcon = new ImageIcon(getClass().getClassLoader().getResource(arrowFileName));
		Image image = arrowIcon.getImage().getScaledInstance(50, 50, Image.SCALE_DEFAULT);
		arrowIcon = new ImageIcon(image);
		
		JButton arrowButton = new JButton();
		arrowButton.setBounds(x,y,width,height);
		arrowButton.setBackground(Color.black);
		arrowButton.setContentAreaFilled(false);
		arrowButton.setIcon(arrowIcon);
		arrowButton.setBorderPainted(false);
		arrowButton.addActionListener(gm.aHandler);
		arrowButton.setActionCommand(command);
		arrowButton.setVisible(true);
		
		bgPanel[bgNum].add(arrowButton);
	}
	public void createPlayerField() {
		
		lifePanel = new JPanel();
		lifePanel.setBounds(50,0,250,50);
		lifePanel.setBackground(Color.black);
		lifePanel.setLayout(new GridLayout(1,5));
		window.add(lifePanel);
		
		ImageIcon lifeICon = new ImageIcon(getClass().getClassLoader().getResource("image//pixelheart.png"));
		Image image = lifeICon.getImage().getScaledInstance(35, 35, Image.SCALE_DEFAULT);
		lifeICon = new ImageIcon(image);
		
		int i =1;
		while(i<6) {
			life[i] = new JLabel();
			life[i].setIcon(lifeICon);
			lifePanel.add(life[i]);
			i++;
		}				
		
		inventoryPanel = new JPanel();
		inventoryPanel.setBounds(650,0,100,50);
		inventoryPanel.setBackground(Color.black);
		inventoryPanel.setLayout(new GridLayout(1,3));
		window.add(inventoryPanel);
				
		// CREATE SWORD
		sword = new JLabel();
		ImageIcon swordIcon = new ImageIcon(getClass().getClassLoader().getResource("image//plain-dagger.png"));
		image = swordIcon.getImage().getScaledInstance(35, 35, Image.SCALE_DEFAULT);
		swordIcon = new ImageIcon(image);
		sword.setIcon(swordIcon);
		inventoryPanel.add(sword);
		
		shield = new JLabel();
		ImageIcon shieldIcon = new ImageIcon(getClass().getClassLoader().getResource("image//dragon-shield.png"));
		image = shieldIcon.getImage().getScaledInstance(35, 35, Image.SCALE_DEFAULT);
		shieldIcon = new ImageIcon(image);
		shield.setIcon(shieldIcon);
		inventoryPanel.add(shield);
		
		lantern = new JLabel();
		ImageIcon lanternIcon = new ImageIcon(getClass().getClassLoader().getResource("image//lanternflame.png"));
		image = lanternIcon.getImage().getScaledInstance(35, 35, Image.SCALE_DEFAULT);
		lanternIcon = new ImageIcon(image);
		lantern.setIcon(lanternIcon);
		inventoryPanel.add(lantern);
	}
	public void createGameOverField() {
		
		titleLabel = new JLabel("",JLabel.CENTER);
		titleLabel.setBounds(200,150,400,200);
		titleLabel.setFont(new Font("Times New Roman",Font.PLAIN,70));
		titleLabel.setForeground(Color.red);
		titleLabel.setVisible(false);
		window.add(titleLabel);
		
		restartButton = new JButton("Click here to restart");
		restartButton.setBounds(340,320,120,50);
		restartButton.setBorder(null);
		restartButton.setBackground(null);
		restartButton.setForeground(Color.white);
		restartButton.setFocusPainted(false);
		restartButton.addActionListener(gm.aHandler);
		restartButton.setActionCommand("restart");
		restartButton.setVisible(false);
		window.add(restartButton);	
	}
	
	// SCREEN GENERATION
	public void generateScreen() {
		// SCREEN1
		createBackgroundImage(1,"image//greenbg700x400.png"); // bgPanelNum, fileName
		createObject(1,450,130,250,200,"image//hut01 200x200.png","Look","Talk","Rest","lookCabin","talkCabin","restCabin");
		createObject(1,300,285,70,52,"image//chest01 x70.png","Look","Talk","Open","lookChest","talkChest","openChest");
		createObject(1,70,180,136,150,"image//guard150.png","Look","Talk","Attack","lookGuard","talkGuard","attackGuard");
		createArrowButton(1,0,170,50,50,"image//leftarrow50x50.png","goScreen2"); 			
		bgPanel[1].add(bgLabel[1]);  // IMPORTANT!  ADD background after objects otherwise it hides all the objects. ADD background image IN THE END!
	    
		// SCREEN2
		createBackgroundImage(2,"image//cave700x400.jpg");
		createObject(2,0,100,70,300,"image//blank100x100.png","Look","Talk","Enter","lookCave","talkCave","enterCave");
		createObject(2,355,250,50,50,"image//blank100x100.png","Look","Talk","Search","lookRoot","talkRoot","searchRoot");
		createArrowButton(2,650,170,50,50,"image//rightarrow50x50.png","goScreen1"); 			
		bgPanel[2].add(bgLabel[2]);	
		
		// SCREEN3
		createBackgroundImage(3,"image//cave.png");
//		createObject(3,250,80,270,250,"image//halloween-3973250_1280.png","Look","Talk","Enter","lookCave","talkCave","enterCave");
		createObject(3,250,80,200,250,"image//werewolf 200x300.png","Look","Talk","Attack","lookMonster","talkMonster","attackMonster");
		createArrowButton(3,650,170,50,50,"image//rightarrow50x50.png","goScreen2"); 		
//		createArrowButton(3,325,50,50,50,"uparrow50x50.png","goScreen1"); 		
		bgPanel[3].add(bgLabel[3]);	
	}

}


SceneChanger



package Main;

public class SceneChanger{
	
	GameManager gm;
	
	public SceneChanger(GameManager gm) {
		
		this.gm = gm;
	}

	public void showScene1() {		

		gm.ui.bgPanel[1].setVisible(true);
		gm.ui.bgPanel[2].setVisible(false);
		gm.ui.messageText.setText("Let's defeat the Demon Lord and save the world!");
			
		gm.stopMusic(gm.currentMusic);
		gm.currentMusic = gm.fieldMusic;
		gm.playMusic(gm.currentMusic);
	}
	public void showScene2() {

		gm.ui.bgPanel[1].setVisible(false);
		gm.ui.bgPanel[3].setVisible(false);
		gm.ui.bgPanel[2].setVisible(true);	
		gm.ui.messageText.setText("");
		
		gm.stopMusic(gm.currentMusic);
		gm.currentMusic = gm.fieldMusic2;
		gm.playMusic(gm.currentMusic);
		
		gm.bm.resetMonsterLife();
	}
	public void showScene3() {

		gm.ui.bgPanel[2].setVisible(false);
		gm.ui.bgPanel[3].setVisible(true);	
					
		gm.stopMusic(gm.currentMusic);	
		
		if(gm.player.defeatWerewolf==false) {
			gm.ui.messageText.setText("OMG the cave is inhabited by a werewolf!");
			gm.currentMusic = gm.battleMusic;
			gm.playMusic(gm.currentMusic);
		}
		else {
			gm.ui.messageText.setText("");
					
		}	
//		gm.ui.messageText.setText("You enter the cave. What is waiting for you inside...?\n\n"
//		+ "*** This is the end of the Demo. Thank you for playing! ***");
//		gm.ui.choiceB1.setVisible(true);
//		gm.ui.choiceB2.setVisible(true);
	}
	public void showGameOverScreen(int currentBgNum) {
		
		gm.ui.bgPanel[currentBgNum].setVisible(false);
		gm.ui.titleLabel.setVisible(true);
		gm.ui.titleLabel.setText("YOU DIED");
		gm.ui.restartButton.setVisible(true);
//		gm.ui.choiceB1.setVisible(false);
//		gm.ui.choiceB2.setVisible(false);
		
		gm.stopMusic(gm.fieldMusic);
		gm.playSE(gm.deathSound);
	}
	public void exitGameOverScreen() {
		
		gm.ui.titleLabel.setVisible(false);
		gm.ui.restartButton.setVisible(false);
		gm.bm.resetMonsterLife();
		gm.player.setPlayerDefaultStatus();
	}
	public void showEndScreen(int currentBgNum) {
		
		gm.ui.bgPanel[currentBgNum].setVisible(false);
		gm.ui.titleLabel.setVisible(true);
		gm.ui.titleLabel.setText("Congratz!");
		gm.ui.messageText.setText("You have completed the Awesome Quest III!\nThanks for playing!");
//		gm.ui.restartButton.setVisible(true);
		
		gm.stopMusic(gm.fieldMusic);
		gm.playSE(gm.awesome);
	}
}


ActionHandler



package Main;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ActionHandler implements ActionListener{
	
	GameManager gm;

	public ActionHandler(GameManager gm) {
		
		this.gm = gm;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
		System.out.println("here?");
		
		String yourChoice = e.getActionCommand();
		
		switch(yourChoice) {
		// Screen 1
		case "lookCabin": gm.ev1.lookCabin();break;
		case "restCabin": gm.ev1.restCabin();break;
		case "talkCabin": gm.ev1.talkCabin();break;
		case "lookChest": gm.ev1.lookChest();break;
		case "openChest": gm.ev1.openChest();break;
		case "talkChest": gm.ev1.talkChest();break;
		case "lookGuard": gm.ev1.lookGuard();break;
		case "attackGuard": gm.ev1.attackGuard();break;
		case "talkGuard": gm.ev1.talkGuard();break;			
		// Screen 2
		case "lookCave": gm.ev2.lookCave();break;
		case "enterCave": gm.ev2.enterCave();break;
		case "talkCave": gm.ev2.talkCave();break;
		case "lookRoot": gm.ev2.lookRoot();break;
		case "searchRoot": gm.ev2.searchRoot();break;
		case "talkRoot": gm.ev2.talkRoot();break;
		// Scene 3
//		case "noway": gm.sChanger.showGameOverScreen(3); gm.ui.messageText.setText("What a fool...");break;
		case "lookMonster": gm.ev3.lookMonster();break;
		case "talkMonster": gm.ev3.talkMonster();break;
		case "attackMonster": gm.ev3.attackMonster();break;
		// Change Screen
		case "goScreen1": gm.sChanger.showScene1();break;
		case "goScreen2": gm.sChanger.showScene2();break;
		// Others
		case "restart": gm.sChanger.exitGameOverScreen(); gm.player.setPlayerDefaultStatus(); gm.sChanger.showScene1();break;			
		}
	}

}


Player



package Main;

public class Player {
	
	GameManager gm;
	
	// PLAYER STATUS
	public int playerMaxLife = 5;
	public int playerLife = 3;
	public int playerStrength = 3;
	public int playerEndurance = 1;
	public int playerAttack;
	public int playerDefense;
	
	public int hasSword;
	public int hasShield;
	public int hasLantern;
	public int weaponPower;
	public int shieldPower;
	
	public boolean defeatWerewolf = false;

	
	public Player(GameManager gm) {
		
		this.gm = gm;		
	}
	public void setPlayerDefaultStatus() {
		
		playerMaxLife = 5;
		playerLife=3;
		playerStrength = 3;
		playerEndurance = 1;
		hasSword=0;
		hasShield=0;
		hasLantern=0;
		weaponPower=0;
		shieldPower=0;
		
		defeatWerewolf = false;
		updatePlayerStatus();
	}
	public void updatePlayerStatus() {
		
		// REMOVE ALL LIFE FIRST
		int i=1;
		while(i<6) { 
			gm.ui.life[i].setVisible(false);
			i++;
		}	
		// RESET LIFE
		int lifeCount = playerLife;
		while(lifeCount!=0) {
			gm.ui.life[lifeCount].setVisible(true);
			lifeCount--;
		}
		playerAttack = playerStrength + weaponPower;
		playerDefense = playerEndurance + shieldPower;
		
		// CHECK PLAYER ITEMS
		if(hasSword==0) {
			gm.ui.sword.setVisible(false);			
		}
		if(hasSword==1) {
			gm.ui.sword.setVisible(true);
		}
		if(hasShield==0) {
			gm.ui.shield.setVisible(false);
		}
		if(hasShield==1) {
			gm.ui.shield.setVisible(true);
		}
		if(hasLantern==0) {
			gm.ui.lantern.setVisible(false);
		}
		if(hasLantern==1) {
			gm.ui.lantern.setVisible(true);
		}
	}

}


SE



package Main;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class SE {
	
	Clip clip;

	public void setFile(URL name)
	{
		try{
			//File file = new File(name);
			AudioInputStream sound = AudioSystem.getAudioInputStream(name);
			clip = AudioSystem.getClip();
			clip.open(sound);
		}
		catch(Exception e)
		{
			
		}
	}
	
	public void play(URL name)
	{
		clip.setFramePosition(0);
		clip.start();
	}
	
	public void loop(URL name)
	{
		clip.loop(Clip.LOOP_CONTINUOUSLY);
	}
	
	public void stop(URL name)
	{
		clip.stop();
	}	

}


Music



package Main;
import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class Music {

	Clip clip;
	
	public void setFile(URL name)
	{
		try{
			AudioInputStream sound = AudioSystem.getAudioInputStream(name);
			clip = AudioSystem.getClip();
			clip.open(sound);
		}
		catch(Exception e)
		{			
		}
	}	
	public void play(URL name)
	{
//		fc.setValue(volume);
		clip.setFramePosition(0);
		clip.start();
	}	
	public void loop(URL name)
	{
		clip.loop(Clip.LOOP_CONTINUOUSLY);
	}	
	public void stop(URL name)
	{		
		clip.stop();
		clip.close();
	}
}


BattleManager



package Main;

import java.util.Random;

import Monster.Monster;
import Monster.Werewolf;

public class BattleManager {
	
	GameManager gm;
	Monster monster;
	Werewolf werewolf = new Werewolf();
	Random randomDie = new Random();
	
	public BattleManager(GameManager gm) {
		
		this.gm = gm;
	}
	public void resetMonsterLife() {
		// add all the monsters if needed
		werewolf.monsterLife = werewolf.monsterMaxLife;
	}
	
	public void setMonster() {		
		monster = werewolf;
		attack();
	}
	
	public void attack() {
		
		int playerDamage = randomDie.nextInt(gm.player.playerAttack)- monster.monsterDefense;
		if(playerDamage<0) {
			playerDamage=0;
		}
		gm.ui.messageText.setText("");
		gm.ui.messageText.append("You attack the " + monster.monsterName + " and give " + playerDamage + " damage!");
		monster.monsterLife -= playerDamage;
		if(monster.monsterLife<1) {
			win();
		}
		else {			
			int monsterDamage = randomDie.nextInt(monster.monsterAttack)-gm.player.playerDefense;
			if(monsterDamage<0) {
				monsterDamage=0;
			}
			gm.player.playerLife -= monsterDamage;
			gm.ui.messageText.append("\nThe " + monster.monsterName + " attacks you and give " + monsterDamage + " damage!");
			if(gm.player.playerLife<1) {
				gm.player.playerLife =0;
				gm.player.updatePlayerStatus();
				lose();
			}	
			else {
				gm.player.updatePlayerStatus();
			}					
		}
		gm.playSE(gm.hitSound);
	}
	public void win() {
		
		gm.ui.messageText.append("\nYou have defeated the monster!");
		
		if(monster==werewolf) {
			gm.player.defeatWerewolf = true;
			gm.stopMusic(gm.currentMusic);
		}
		else {			
		}
	}
	public void lose() {
	
		gm.ui.messageText.append("\nYou died!!");
		gm.sChanger.showGameOverScreen(3);
	}

}


Event01



package Event;

import Main.GameManager;

public class Event01{
	
	public GameManager gm;

	public Event01(GameManager gm) {
		
		this.gm = gm;
	}
	
	public void lookCabin() {
		gm.ui.messageText.setText("This is your home.");
	}
	public void talkCabin() {
		gm.ui.messageText.setText("Who are you talking to?");
	}
	public void restCabin() {
		
		if(gm.player.defeatWerewolf==true) {
			gm.sChanger.showEndScreen(1);
		}		 
		else {
			if(gm.player.playerLife != gm.player.playerMaxLife) {
				gm.ui.messageText.setText("You rest at the home.\n(Your LIFE has recovered)");
				gm.player.playerLife++; 
				gm.player.updatePlayerStatus();
				
				gm.playSE(gm.healSound);
			}	
			else {
				gm.ui.messageText.setText("Your LIFE is full.");
			}
		}
	}
	public void lookChest() {
		gm.ui.messageText.setText("A chest is on the ground.");
	}
	public void talkChest() {
		gm.ui.messageText.setText("You talk to the chest but it says nothing.");
	}
	public void openChest() {
		gm.ui.messageText.setText("You open the chest and find a sword!"); 
		gm.ui.sword.setVisible(true);
		gm.player.hasSword=1;
		gm.player.weaponPower=2;
		gm.player.updatePlayerStatus();
		gm.playSE(gm.chestopen);
	}
	public void lookGuard() {
		gm.ui.messageText.setText("A guard is standing in front of you.");
	}
	public void talkGuard() {
		if(gm.player.hasSword==0) {
			gm.ui.messageText.setText("Guard: Don't go any further without a weapon! \nYou should check the chest over there."); 
			gm.playSE(gm.guard01);
		}
		else {
			gm.ui.messageText.setText("Guard: Don't go any further without a weapon! \n...Oh never mind. It seems you already have it."); 
			gm.playSE(gm.guard06);
		}
	}
	public void attackGuard() {
		if(gm.player.hasShield==0) {
			if(gm.player.hasSword==0) {
				if(gm.player.playerLife!=1) {
					gm.ui.messageText.setText("Guard: Hey, don't be stupid!\n(The guard hits you back and your life decreases by 1)");
					gm.player.playerLife--;
//					gm.player.updatePlayerStatus();
					
					gm.playSE(gm.hitSound);
					gm.playSE(gm.guard02);
				}
				else if(gm.player.playerLife==1) {
					gm.ui.messageText.setText("Guard: What a fool...");
					gm.player.playerLife--;
//					gm.player.updatePlayerStatus();
					gm.sChanger.showGameOverScreen(1);
//					gm.playSE(gm.guard03);
				}
			}
			else {
				gm.ui.messageText.setText("Guard: Oh, shit!\n(You defeated the guard and got his shield!)");
				gm.ui.shield.setVisible(true);
				gm.player.hasShield=1;
				gm.player.shieldPower=1;
//				gm.player.updatePlayerStatus();
				gm.playSE(gm.hitSound);
				gm.playSE(gm.guard04);
			}
			gm.player.updatePlayerStatus();
		}
		else {
			gm.ui.messageText.setText("Guard: Just leave me alone.");
			gm.playSE(gm.guard05);
		}
	}	
}


Event02



package Event;

import Main.GameManager;

public class Event02 {
	
	public GameManager gm;
	
	public Event02(GameManager gm) {
		
		this.gm = gm;		
	}
	
	public void lookCave() {
		gm.ui.messageText.setText("It's a cave!"); 
	}
	public void talkCave() {
		gm.ui.messageText.setText("You hear the echo of your voice.");
	}
	public void enterCave() {
		if(gm.player.hasLantern==0) {
			gm.ui.messageText.setText("It's too dark to enter.");
		}
		else {
			gm.sChanger.showScene3();
//			gm.playSE(gm.enter);
		}
	}
	public void lookRoot() {
		gm.ui.messageText.setText("There is something at the tree.");
	}
	public void talkRoot() {
		gm.ui.messageText.setText("They say plants grow well if you talk to them but this tree doesn't look like it needs encouragement.");
	}	
	public void searchRoot() {
		gm.ui.messageText.setText("You find a lantern!"); 
		gm.ui.lantern.setVisible(true);
		gm.player.hasLantern=1;
		gm.playSE(gm.chestopen);
	}
		
}


Event03



package Event;

import Main.GameManager;

public class Event03 {
	
	GameManager gm;
	
	public Event03(GameManager gm) {
		
		this.gm = gm;		
	}
	
	public void lookMonster() {
		
		if(gm.player.defeatWerewolf==true) {
			gm.ui.messageText.setText("The monster is dead...");
		}
		else {
			gm.ui.messageText.setText("It's a monster!");
		}
	}
	public void talkMonster() {
		
		if(gm.player.defeatWerewolf==true) {
			gm.ui.messageText.setText("Monster: .......");
		}
		else {
			gm.ui.messageText.setText("Monster: DIE YOU FOOL!");
		}
	}
	public void attackMonster() {
		
		if(gm.player.defeatWerewolf==true) {
			gm.ui.messageText.setText("He is already dead...");
		}
		else {
			gm.bm.setMonster();
		}
		
	}
}

Monster



package Monster;

public class Monster {
	
	public String monsterName;
//	public String status;
	public int monsterMaxLife;
	public int monsterLife;
	public int monsterAttack;
	public int monsterDefense;

}


Werewolf



package Monster;

public class Werewolf extends Monster{
		
	public Werewolf() {
		
		monsterName = "Werewolf";
//		status = "alive";
		monsterMaxLife = 5;
		monsterLife = 5;
		monsterAttack = 5; // 0-4
		monsterDefense = 1;
	}
}


[Java Code Sample] Point and click adventure game

 

Here's the full source code for the point and click adventure game that I made.


Screenshot:




Right clicking on certain locations on the screen will open a menu.

Then you can choose a command such as "Look", "Take", "Talk" etc.



Class structure:

Resources that I used:


This is kind of a long code so please check my video tutorial for more detail.



Code:


GameManager class



package Main;

import java.net.URL;

import Event.Event01;
import Event.Event02;

public class GameManager {
	
	ActionHandler aHandler = new ActionHandler(this);
	public UI ui = new UI(this);
	public Player player = new Player(this);
	public SceneChanger sChanger = new SceneChanger(this);
	Music music = new Music();
	SE se = new SE();

	public Event01 ev1 = new Event01(this);
	public Event02 ev2 = new Event02(this);
	
	// SOUND
	public URL fieldMusic = getClass().getClassLoader().getResource("audio//bensound-acousticbreeze.wav");
	public URL fieldMusic2 = getClass().getClassLoader().getResource("audio//bensound-ofeliasdream.wav");
	public URL deathSound = getClass().getClassLoader().getResource("audio//deathSound.wav");
	public URL hitSound = getClass().getClassLoader().getResource("audio//hitSound.wav");
	public URL healSound = getClass().getClassLoader().getResource("audio//healSound.wav");
	public URL itemSound = getClass().getClassLoader().getResource("audio//itemSound.wav");
	public URL enterSound = getClass().getClassLoader().getResource("audio//enterSound.wav");
	public URL guard_01 = getClass().getClassLoader().getResource("audio//guard_01.wav");
	public URL guard_02 = getClass().getClassLoader().getResource("audio//guard_02.wav");
	public URL guard_03 = getClass().getClassLoader().getResource("audio//guard_03.wav");
	public URL guard_04 = getClass().getClassLoader().getResource("audio//guard_04.wav");
	public URL currentMusic;

	public static void main(String[] args) {
		
		new GameManager();

	}
	public GameManager() {
		
		currentMusic = fieldMusic;
		playMusic(currentMusic);
		
		player.setPlayerDefaultStatus();
		sChanger.showSceen1();
	}
	
	public void playSE(URL url) {
		
		se.setFile(url);
		se.play(url);
	}
	public void playMusic(URL url) {
		
		music.setFile(url);
		music.play(url);
		music.loop(url);		
	}
	public void stopMusic(URL url) {
		
		music.stop(url);
	}
}


UI class



package Main;

import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class UI {

	GameManager gm;
	
	JFrame window;
	public JTextArea messageText;
	public JPanel bgPanel[] = new JPanel[10];
	public JLabel bgLabel[] = new JLabel[10];
	
	// PLAYER UI
	JPanel lifePanel;
	JLabel lifeLabel[] = new JLabel[6];
	JPanel inventoryPanel;
	public JLabel swordLabel, shieldLabel, lanternLabel;
	
	// GAME OVER UI
	public JLabel titleLabel;
	public JButton restartButton;
	
	
	public UI(GameManager gm) {
		
		this.gm = gm;
		
		createMainField();
		createPlayerField();
		createGameOverField();
		generateScene();
		
		window.setVisible(true);
	}
	
	public void createMainField() {
		
		window = new JFrame("AWESOME QUEST III");
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		window.setLayout(null);
		
		messageText = new JTextArea("THIS IS SMAPLE TEXT");
		messageText.setBounds(50,410,700,150);
		messageText.setBackground(Color.black);
		messageText.setForeground(Color.white);
		messageText.setEditable(false);
		messageText.setLineWrap(true);
		messageText.setWrapStyleWord(true);
		messageText.setFont(new Font("Book Antiqua", Font.PLAIN, 26));
		window.add(messageText);
	}
	public void createBackground(int bgNum, String bgFileName) {
		
		bgPanel[bgNum] = new JPanel();
		bgPanel[bgNum].setBounds(50,50,700,350);
		bgPanel[bgNum].setBackground(Color.black);
		bgPanel[bgNum].setLayout(null);
		bgPanel[bgNum].setVisible(false); 
		window.add(bgPanel[bgNum]);
		
		bgLabel[bgNum] = new JLabel();
		bgLabel[bgNum].setBounds(0,0,700,350);
		
		ImageIcon bgIcon = new ImageIcon(getClass().getClassLoader().getResource(bgFileName));
		bgLabel[bgNum].setIcon(bgIcon);				
	}
	public void createObject(int bgNum, int objx, int objy, int objWidth, int objHeight, String objFileName, 
			String choice1Name, String choice2Name, String choice3Name, String choice1Command, String Choice2Command, String Choice3Command) {
		
		// CREATE POP MENU
		JPopupMenu popMenu = new JPopupMenu();
		// CREATE POP MENU ITEMS
		JMenuItem menuItem[] = new JMenuItem[4]; // Use [1],[2],[3]
		menuItem[1] = new JMenuItem(choice1Name);
		menuItem[1].addActionListener(gm.aHandler);
		menuItem[1].setActionCommand(choice1Command);
		popMenu.add(menuItem[1]);
		
		menuItem[2] = new JMenuItem(choice2Name);
		menuItem[2].addActionListener(gm.aHandler);
		menuItem[2].setActionCommand(Choice2Command);
		popMenu.add(menuItem[2]);
		
		menuItem[3] = new JMenuItem(choice3Name);
		menuItem[3].addActionListener(gm.aHandler);
		menuItem[3].setActionCommand(Choice3Command);
		popMenu.add(menuItem[3]);
		
		// CREATE OBJECTS
		JLabel objectLabel = new JLabel();
		objectLabel.setBounds(objx,objy,objWidth,objHeight);
//		objectLabel.setOpaque(true);
//		objectLabel.setBackground(Color.blue);
		
		ImageIcon objectIcon = new ImageIcon(getClass().getClassLoader().getResource(objFileName));
		objectLabel.setIcon(objectIcon);
		
		objectLabel.addMouseListener(new MouseListener() {

			public void mouseClicked(MouseEvent e) {}
			public void mousePressed(MouseEvent e) {
				
				if(SwingUtilities.isRightMouseButton(e)) {
					popMenu.show(objectLabel, e.getX(), e.getY());
				}
				
			}
			public void mouseReleased(MouseEvent e) {}
			public void mouseEntered(MouseEvent e) {}
			public void mouseExited(MouseEvent e) {}
			
		});
		
		
		bgPanel[bgNum].add(objectLabel);
		
		
	}
	public void createArrowButton(int bgNum, int x, int y, int width, int height, String arrowFileName, String command) {
		
		ImageIcon arrowIcon = new ImageIcon(getClass().getClassLoader().getResource(arrowFileName));
		
		JButton arrowButton = new JButton();
		arrowButton.setBounds(x, y, width, height);
		arrowButton.setBackground(null);
		arrowButton.setContentAreaFilled(false);
		arrowButton.setFocusPainted(false);
		arrowButton.setIcon(arrowIcon);
		arrowButton.addActionListener(gm.aHandler);
		arrowButton.setActionCommand(command);
		arrowButton.setBorderPainted(false);
		
		bgPanel[bgNum].add(arrowButton);
	}
	public void createPlayerField() {
		
		lifePanel = new JPanel();
		lifePanel.setBounds(50,0,250,50);
		lifePanel.setBackground(Color.black);
		lifePanel.setLayout(new GridLayout(1,5));
		window.add(lifePanel);
		
		ImageIcon lifeIcon = new ImageIcon(getClass().getClassLoader().getResource("heart.png"));
		Image image = lifeIcon.getImage().getScaledInstance(35, 35, Image.SCALE_DEFAULT);
		lifeIcon = new ImageIcon(image);
		
		int i=1;
		while(i<6) {
			lifeLabel[i] = new JLabel();
			lifeLabel[i].setIcon(lifeIcon);
			lifePanel.add(lifeLabel[i]);
			i++;
		}
		
		inventoryPanel = new JPanel();
		inventoryPanel.setBounds(650,0,100,50);
		inventoryPanel.setBackground(Color.black);
		inventoryPanel.setLayout(new GridLayout(1,3));
		window.add(inventoryPanel);
		
		// CREATE  ITEMS
		swordLabel = new JLabel();
		ImageIcon swordIcon = new ImageIcon(getClass().getClassLoader().getResource("plain-dagger.png"));
		image = swordIcon.getImage().getScaledInstance(35, 35, Image.SCALE_DEFAULT);
		swordIcon = new ImageIcon(image);
		swordLabel.setIcon(swordIcon);
		inventoryPanel.add(swordLabel);
		
		shieldLabel = new JLabel();
		ImageIcon shieldIcon = new ImageIcon(getClass().getClassLoader().getResource("dragon-shield.png"));
		image = shieldIcon.getImage().getScaledInstance(35, 35, Image.SCALE_DEFAULT);
		shieldIcon = new ImageIcon(image);
		shieldLabel.setIcon(shieldIcon);
		inventoryPanel.add(shieldLabel);
		
		lanternLabel = new JLabel();
		ImageIcon lanternIcon = new ImageIcon(getClass().getClassLoader().getResource("lanternflame.png"));
		image = lanternIcon.getImage().getScaledInstance(35, 35, Image.SCALE_DEFAULT);
		lanternIcon = new ImageIcon(image);
		lanternLabel.setIcon(lanternIcon);
		inventoryPanel.add(lanternLabel);
		
	}
	public void createGameOverField() {
		
		titleLabel = new JLabel("",JLabel.CENTER);
		titleLabel.setBounds(200,150,400,200);
		titleLabel.setForeground(Color.red);
		titleLabel.setFont(new Font("Times New Roman", Font.PLAIN, 70));
		titleLabel.setVisible(false);
		window.add(titleLabel);
		
		restartButton = new JButton();
		restartButton.setBounds(340,320,120,50);
		restartButton.setBorder(null);
		restartButton.setBackground(null);
		restartButton.setForeground(Color.white);
		restartButton.setFocusPainted(false);
		restartButton.addActionListener(gm.aHandler);
		restartButton.setActionCommand("restart");
		restartButton.setVisible(false);
		window.add(restartButton);
	}
	
	public void generateScene() {
		
		// SCENE 1
		createBackground(1,"greenbg700x350.png");
		createObject(1,440,140,200,200,"hut 200x200.png", "Look", "Talk", "Rest", "lookHut", "talkHut", "restHut");
		createObject(1,70,180,150,150,"guard 150x150.png", "Look", "Talk", "Attack", "lookGuard", "talkGuard", "attackGuard");
		createObject(1,310,280,70,70,"chest 70x70.png", "Look", "Talk", "Open", "lookChest", "talkChest", "openChest");
		createArrowButton(1,0,150,50,50,"leftarrow 50x50.png","goScene2");
		bgPanel[1].add(bgLabel[1]);
		
		// SCENE 2
		createBackground(2,"caveoutside 700x350.jpg");
		createObject(2,0,100,100,300,"blank100x100.png", "Look", "Talk", "Enter", "lookCave", "talkCave", "enterCave");
		createObject(2,355,250,50,50,"blank100x100.png", "Look", "Talk", "Search", "lookRoot", "talkRoot", "searchRoot");
		createArrowButton(2,650,150,50,50,"rightarrow 50x50.png","goScene1");
		bgPanel[2].add(bgLabel[2]);
		
		// SCENE 3
		createBackground(3,"cave 700x350.png");
		createArrowButton(3,650,150,50,50,"rightarrow 50x50.png","goScene2");
		bgPanel[3].add(bgLabel[3]);
	}
}



SceneChanger class



package Main;

public class SceneChanger {
	
	GameManager gm;

	public SceneChanger(GameManager gm) {
		
		this.gm = gm;
	}
	
	public void showSceen1() {
		
		gm.ui.bgPanel[1].setVisible(true);
		gm.ui.bgPanel[2].setVisible(false);	
		gm.ui.messageText.setText("Let's defeat the Demon Lord and save the world!");
		
		gm.stopMusic(gm.currentMusic);
		gm.currentMusic = gm.fieldMusic;
		gm.playMusic(gm.currentMusic);
	}
	public void showSceen2() {
		
		gm.ui.bgPanel[1].setVisible(false);
		gm.ui.bgPanel[2].setVisible(true);	
		gm.ui.bgPanel[3].setVisible(false);
		gm.ui.messageText.setText("");
		
		gm.stopMusic(gm.currentMusic);
		gm.currentMusic = gm.fieldMusic2;
		gm.playMusic(gm.currentMusic);
	}
	public void showSceen3() {
		
		gm.playSE(gm.enterSound);
		gm.ui.bgPanel[2].setVisible(false);
		gm.ui.bgPanel[3].setVisible(true);	
		gm.ui.messageText.setText("You enter the cave. What is waiting for you inside...\n\n"
				+ "*** This is the end of the demo. Thank you for playing!!! ***");
	}
	public void showGameOverScreen(int currentBgNum) {
		
		gm.ui.bgPanel[currentBgNum].setVisible(false);
		gm.ui.titleLabel.setVisible(true);
		gm.ui.titleLabel.setText("YOU DIED");
		gm.ui.restartButton.setVisible(true);
		gm.ui.restartButton.setText("Click here to restart");
		
		gm.stopMusic(gm.currentMusic);
		gm.playSE(gm.deathSound);
	}
	public void existGameOverScreen() {
		
		gm.ui.titleLabel.setVisible(false);
		gm.ui.restartButton.setVisible(false);
		gm.player.setPlayerDefaultStatus();
	}
}



ActionHandler class



package Main;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ActionHandler implements ActionListener{
	
	GameManager gm;

	public ActionHandler(GameManager gm) {
		
		this.gm = gm;
	}
	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		String yourChoice = e.getActionCommand();
		
		switch(yourChoice) {
		// SCENE 1
		case "lookHut": gm.ev1.lookHut(); break;
		case "talkHut": gm.ev1.talkHut(); break;
		case "restHut": gm.ev1.restHut(); break;
		case "lookGuard": gm.ev1.lookGuard(); break;
		case "talkGuard": gm.ev1.talkGuard(); break;
		case "attackGuard": gm.ev1.attackGuard(); break;
		case "lookChest": gm.ev1.lookChest(); break;
		case "talkChest": gm.ev1.talkChest(); break;
		case "openChest": gm.ev1.openChest(); break;
		// SCENE 2
		case "lookCave": gm.ev2.lookCave();break;
		case "talkCave": gm.ev2.talkCave();break;
		case "enterCave": gm.ev2.enterCave();break;
		case "lookRoot": gm.ev2.lookRoot();break;
		case "talkRoot": gm.ev2.talkRoot();break;
		case "searchRoot": gm.ev2.searchRoot();break;
 		// Change Scenes
		case "goScene1": gm.sChanger.showSceen1(); break;
		case "goScene2": gm.sChanger.showSceen2(); break;
		// OTHERS
		case "restart": gm.sChanger.existGameOverScreen(); gm.sChanger.showSceen1(); break;
		}
	}

}



Player class



package Main;

public class Player {
	
	GameManager gm;
	
	public int playerMaxLife;
	public int playerLife;
	
	public int hasSword;
	public int hasShield;
	public int hasLantern;
	
	public Player(GameManager gm) {
		
		this.gm = gm;
	}
	
	public void setPlayerDefaultStatus() {
		
		playerMaxLife = 5;
		playerLife = 3;
		hasSword = 0;
		hasShield = 0;
		hasLantern = 0;
		
		updatePlayerStatus();
	}
	public void updatePlayerStatus() {
		
		// REMOVE ALL LIFE ICON
		int i =1;
		while(i<6) {
			gm.ui.lifeLabel[i].setVisible(false);
			i++;
		}
		
		int lifeCount = playerLife;
		while(lifeCount!=0) {
			gm.ui.lifeLabel[lifeCount].setVisible(true);
			lifeCount--;
		}
		
		// CHECK PLAYER ITEMS
		if(hasSword==0) {
			gm.ui.swordLabel.setVisible(false);
		}
		if(hasSword==1) {
			gm.ui.swordLabel.setVisible(true);
		}
		if(hasShield==0) {
			gm.ui.shieldLabel.setVisible(false);
		}
		if(hasShield==1) {
			gm.ui.shieldLabel.setVisible(true);
		}
		if(hasLantern==0) {
			gm.ui.lanternLabel.setVisible(false);
		}
		if(hasLantern==1) {
			gm.ui.lanternLabel.setVisible(true);
		}
	}

}



SE class



package Main;

import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class SE {
	
	Clip clip;
	
	public void setFile(URL name) {
		
		try {
			AudioInputStream sound = AudioSystem.getAudioInputStream(name);
			clip = AudioSystem.getClip();
			clip.open(sound);
		}
		catch(Exception e) {
			
		}
	}
	
	public void play(URL name) {
		
		clip.setFramePosition(0);
		clip.start();
	}
	
	public void loop(URL name) {
		
		clip.loop(Clip.LOOP_CONTINUOUSLY);
	}
	public void stop(URL name) {
		
		clip.stop();
	}
}



Music



package Main;

import java.net.URL;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

public class Music {

	Clip clip;
	
	public void setFile(URL name) {
		
		try {
			AudioInputStream sound = AudioSystem.getAudioInputStream(name);
			clip = AudioSystem.getClip();
			clip.open(sound);
		}
		catch(Exception e) {
			
		}
	}
	
	public void play(URL name) {
		
		clip.setFramePosition(0);
		clip.start();
	}
	
	public void loop(URL name) {
		
		clip.loop(Clip.LOOP_CONTINUOUSLY);
	}
	public void stop(URL name) {
		
		clip.stop();
	}
}



Event01



package Event;

import Main.GameManager;

public class Event01 {
	
	GameManager gm;
	
	public Event01(GameManager gm) {
		
		this.gm = gm;
	}
	
	public void lookHut() {
		gm.ui.messageText.setText("This is your house."); 
	}
	public void talkHut() {
		gm.ui.messageText.setText("Who are you talking to?");
	}
	public void restHut() {
		
		if(gm.player.playerLife != gm.player.playerMaxLife) {
			gm.ui.messageText.setText("You rest at the house.\n(Your life has recovered)");	
			gm.player.playerLife++;
			gm.player.updatePlayerStatus();
			gm.playSE(gm.healSound);
		}
		else {
			gm.ui.messageText.setText("Your life is full.");
		}
			
	}
	public void lookGuard() {
		gm.ui.messageText.setText("A guard is standing in front of you.");		
	}
	public void talkGuard() {
		gm.ui.messageText.setText("Guard: Don't go any further without a weapon!\nYou should check the chest over there!");	
		gm.playSE(gm.guard_01);
	}
	public void attackGuard() {
		if(gm.player.hasShield==0) {
			if(gm.player.hasSword==0) {
				if(gm.player.playerLife!=1) {
					gm.ui.messageText.setText("Guard: Hey, don't be stupid!\n(The guard hits you back and your life decreases by 1)");
					gm.player.playerLife--;
					
					gm.playSE(gm.guard_02);
					gm.playSE(gm.hitSound);
				}
				else if(gm.player.playerLife==1) {
					gm.ui.messageText.setText("Guard: What a fool.");
					gm.player.playerLife--;
					gm.sChanger.showGameOverScreen(1);
				}
			}
			else if(gm.player.hasSword==1) {
				gm.ui.messageText.setText("Guard: Oh, shit! \n(You have defeated the guard and gotten his shield!)");
				gm.player.hasShield=1;	
				
				gm.playSE(gm.guard_03);
				gm.playSE(gm.hitSound);
			}
			gm.player.updatePlayerStatus();
		}
		else {
			gm.ui.messageText.setText("Guard: Just leave me alone.");
			gm.playSE(gm.guard_04);
		}
			
	}
	public void lookChest() {
		gm.ui.messageText.setText("A chest is on the ground.");		
	}
	public void talkChest() {
		gm.ui.messageText.setText("You talk to the chest but it says nothing.");		
	}
	public void openChest() {
		if(gm.player.hasSword==0) {
			gm.ui.messageText.setText("You open the chest and find a sword!");	
			gm.player.hasSword=1;
			gm.player.updatePlayerStatus();
			gm.playSE(gm.itemSound);
		}
		else {
			gm.ui.messageText.setText("There's nothing inside...");	
		}
			
	}

}


Event02


package Event;

import Main.GameManager;

public class Event02 {

	public GameManager gm;
	
	public Event02(GameManager gm) {
		
		this.gm = gm;
	}
	
	public void lookCave() {
		gm.ui.messageText.setText("It's a cave!");
	}
	public void talkCave() {
		gm.ui.messageText.setText("You hear the echo of your voice.");
	}
	public void enterCave() {
		if(gm.player.hasLantern==0) {
			gm.ui.messageText.setText("It's too dark to enter.");
		}
		else {
			gm.sChanger.showSceen3();
		}		
	}
	public void lookRoot() {
		gm.ui.messageText.setText("This is a large tree.");
	}
	public void talkRoot() {
		gm.ui.messageText.setText("They say plant grows well if you talk to but this tree doesn't look like it needs encouragement.");
	}
	public void searchRoot() {
		if(gm.player.hasLantern==0) {
			gm.ui.messageText.setText("You find a lantern!");
			gm.player.hasLantern = 1;
			gm.player.updatePlayerStatus();
			gm.playSE(gm.itemSound);
		}
		else {
			gm.ui.messageText.setText("You didn't find anythng.");
		}
		
	}
}




[Java Code Sample] Loading multiple images in a folder

Ever wondered about how to load multiple images in a folder at the same time? 

I was trying to load 2D tile images for my game but loading them one by one was pretty tiresome. 

So I tried to find a way to load them simultaneously and this is what I did.


Please check my video tutorial for the details:



Code:



import java.awt.GridLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
	
	BufferedImage [] allImages;
	
    public static void main(String[] args) {
		
		new Main();

	}
    public Main() {
    	
    	// If load images from res folder
    	File path = new File("res");
    	// If load images in a folder on desktop
//    	File path = new File("C:\Users\User\Desktop\folder name");
    	
    	File[] allFiles = path.listFiles();
    	
    	allImages = new BufferedImage[allFiles.length];
    	
    	JFrame window = new JFrame();
    	window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    	window.setLayout(new GridLayout(5,5));
    	
    	JLabel label[] = new JLabel[allFiles.length];
    	
    	for(int i = 0; i < allFiles.length; i++) {
    		
    		try{
    			allImages[i] = ImageIO.read(allFiles[i]);
    			
    			label[i] = new JLabel();
    			
    			ImageIcon icon = new ImageIcon(allImages[i]);
    			label[i].setIcon(icon);
    			window.add(label[i]);
    			
    		}catch(IOException e) {
    			
    		}
    	}
    	window.pack();
    	window.setVisible(true);
    }
}



Result:


All the tile images in the folder are loaded and displayed.

Thursday, April 15, 2021

[Java Code Sample] Combine multiple buffered images into a single image

 

Here's a sample code to merge multiple images into a single image.


There are two versions.  

The version one is to place two images side by side and merge them as a single image. 

The version two is to merge two images on the same spot.


If you want to follow the process step by step, please check my video tutorial:




Code:



import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
	
	BufferedImage image1;
	BufferedImage image2;
	
	public static void main(String[] args){

		new Main();
	}
	public Main() {
		

		JFrame window = new JFrame();
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		BufferedImage combinedImage;
		
		try {
			// VERSION 1
			image1 = ImageIO.read(getClass().getClassLoader().getResource("town 800x600.png"));
			image2 = ImageIO.read(getClass().getClassLoader().getResource("girl 800x600.png"));
			
			combinedImage = new BufferedImage(800,600, BufferedImage.TYPE_INT_ARGB);
			
			Graphics2D g = combinedImage.createGraphics();
			
			g.drawImage(image1, 0, 0, null);
			g.drawImage(image2, 0, 0, null);
			// VERSION 1 END
			
			// VERSION 2
//			image1 = ImageIO.read(getClass().getClassLoader().getResource("11C.png"));
//			image2 = ImageIO.read(getClass().getClassLoader().getResource("12C.png"));
//			
//			int width = image1.getWidth() + image2.getWidth();
//			int height = Math.max(image1.getHeight(), image2.getHeight());
//			
//			combinedImage = new BufferedImage(width, height,BufferedImage.TYPE_INT_ARGB);
//			
//			Graphics2D g = combinedImage.createGraphics();
//			
//			g.drawImage(image1, 0, 0, null);
//			g.drawImage(image2, image1.getWidth(), 0, null);
			// VERSION 2 END
			
			g.dispose();
			
			JLabel label = new JLabel();
			window.add(label);
			label.setIcon(new ImageIcon(combinedImage));
			
            // Export the combined image to desktop
			try {
				ImageIO.write(combinedImage, "PNG", new File("C:\\Users\\User\\Desktop\\combinedImage.png"));
			}catch(IOException e) {
				
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		window.pack();
		window.setVisible(true);
		
	}
}








Result:

Version 1


+





Version 2











[Java Code Sample] Scrolling Text (Like end credit roll text)

 

Here's a sample code to create a scrolling/moving text just like ending credit roll text for video games or movies.


Video tutorial:



Code:




public class Main {

	public static void main(String[] args) {
		
		Screen screen = new Screen();
	}

}



import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Screen extends JPanel implements ActionListener{
	
	Timer creditTimer = new Timer(5,this);
	String text;
	int textY = 600;	
	
	public Screen() {
		
		JFrame window = new JFrame("Credit Roll Test");
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setLocationRelativeTo(null);
		window.add(this);
		window.setVisible(true);
		this.setBackground(Color.black);
		
		text = "Congratulations!\n\n"
				+ "Story\n"
				+ "Yuji Horii\n\n"
				+ "Illustration\n"
				+ "Akira Toriyama\n\n"
				+ "Music\n"
				+ "Koichi Sugiyama\n\n\n\n\n\n\n\n\n\n\n\n\n"
				+ "Thank you for playing!";
		
		creditTimer.start();
	}
	
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		
		Graphics2D g2d = (Graphics2D)g;
		
		g2d.setFont(new Font("Times New Roman", Font.PLAIN, 28));
		g2d.setColor(Color.white);
		g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
		
		int y = textY;
		
		for(String line : text.split("\n")) {
			
			int stringLength = (int)g2d.getFontMetrics().getStringBounds(line, g2d).getWidth();
			int x = getWidth()/2 - stringLength/2;
			g2d.drawString(line, x, y +=28);
		}	
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		
		System.out.println(textY);
		
		textY--;
		if(textY < -320) {
			creditTimer.stop();
		}
		
		repaint();
	}

}


end


[Java Code Sample] Fade in and fade out image - Edit alpha channel

 

Here's a sample code to change image's opacity so image gradually appears/disappears.


Video tutorial:


Code:


import java.awt.Color;

import javax.swing.JFrame;

public class Main {

	public static void main(String[] args) {
		
		new Main();

	}
	public Main() {
	
		JFrame window = new JFrame();
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		
		Screen screen = new Screen();
		window.add(screen);
		
		window.setVisible(true);
	};

}

(If you want to make the image gradually disappear, start the alphaValue from 1f and decrease it until it hits 0 in the actionPerformed method)


import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

public class Screen extends JPanel implements ActionListener{
	
	Timer alphaTimer = new Timer(20,this);
	BufferedImage buffImage;
	
	float alphaValue = 0f;
//	float alphaValue = 1f;
		
	
	public Screen() {
		
		JLabel label = new JLabel();
		ImageIcon icon = new ImageIcon(getClass().getClassLoader().getResource("backgraoundimage.png"));
		label.setIcon(icon);
		this.add(label);
		
		loadBufferedImage();
		alphaTimer.start();
		
	}
	public void loadBufferedImage() {
		
		buffImage = null;
		
		try {
			buffImage = ImageIO.read(getClass().getClassLoader().getResource("characterimage.png"));
			
		}catch(IOException e) {
			
		}
	}
	public void paint(Graphics g) {
		
		super.paint(g);
		Graphics2D g2d = (Graphics2D)g;
		
		g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alphaValue));		
		g2d.drawImage(buffImage, 50, 20, null);
		
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		
//		alphaValue = alphaValue -0.01f;
//		
//		if(alphaValue < 0) {
//			alphaValue = 0;
//			alphaTimer.stop();
//		}
				
		alphaValue = alphaValue +0.01f;
		
		if(alphaValue > 1) {
			alphaValue = 1;
			alphaTimer.stop();
		}
		
		repaint();		
	}
}




end

[Java Code Sample] Add gray filter to image

 

Here's a sample Java code to add gray filter to an image.


Video tutorial:




Here's the code:




import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;

import javax.swing.GrayFilter;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
	
	JFrame window;
	JLabel pictureLabel;
	ImageIcon pic;

	public static void main(String[] args) {
		
		new Main();

	}
	public Main() {
				
		window = new JFrame();
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setLayout(null);
		
		pictureLabel = new JLabel();
		pictureLabel.setBounds(150,50,500,500);
		window.add(pictureLabel);
		
		pic = new ImageIcon(getClass().getClassLoader().getResource("ps.png"));
		
		pictureLabel.setIcon(pic);
		
		window.setVisible(true);
		
		addGrayFilter();
	}
	public void addGrayFilter() {
		
		Image colorImage = pic.getImage();
		ImageFilter iFilter = new GrayFilter(false, 10);
		ImageProducer iProducer = new FilteredImageSource(colorImage.getSource(), iFilter);
		Image grayImage = Toolkit.getDefaultToolkit().createImage(iProducer);
		ImageIcon grayIcon = new ImageIcon(grayImage);
		pictureLabel.setIcon(grayIcon);
	}
}

Result:

Without gray filter:



With gray filter:



end


Wednesday, April 14, 2021

[Java Code Sample] Create Cookie Clicker Game

 

Here's a sample code to create Cookie Clicker game.


Here's a screenshot:


The UI is pretty basic but it works like normal cookie clicker. 

You can get cookies by clicking the cookie image and purchase items by spending cookies that you made.


Video tutorial:



Code:


import java.awt.Color;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;

public class CookieMain {
	
	JLabel counterLabel, perSecLabel;
	JButton button1, button2, button3, button4;
	int cookieCounter, timerSpeed, cursorNumber, cursorPrice, grandpaNumber, grandpaPrice;
	double perSecond;
	boolean timerOn, grandpaUnlocked;
	Font font1, font2;
	CookieHandler cHandler = new CookieHandler();
	Timer timer;
	JTextArea messageText;
	MouseHandler mHandler = new MouseHandler();

	public static void main(String[] args) {
		
		new CookieMain();

	}
	public CookieMain(){
		
		timerOn = false;
		perSecond = 0;
		cookieCounter = 0;
		cursorNumber = 0;
		cursorPrice = 10;
		grandpaNumber = 0;
		grandpaPrice = 100;
		grandpaUnlocked = false;
		
		createFont();
		createUI();
	}
	public void createFont(){
		
		font1 = new Font("Comic Sans MS", Font.PLAIN, 32);
		font2 = new Font("Comic Sans MS", Font.PLAIN, 15);
		
	}
	public void createUI(){
		
		JFrame window = new JFrame();
		window.setSize(800, 600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		window.setLayout(null);
		
		JPanel cookiePanel = new JPanel();
		cookiePanel.setBounds(100, 220, 200, 200);
		cookiePanel.setBackground(Color.black);
		window.add(cookiePanel);
		
		ImageIcon cookie = new ImageIcon(getClass().getClassLoader().getResource("cookie200x200.png"));
		
		JButton cookieButton = new JButton();
		cookieButton.setBackground(Color.black);
		cookieButton.setFocusPainted(false);
		cookieButton.setBorder(null);
		cookieButton.setIcon(cookie);
		cookieButton.addActionListener(cHandler);
		cookieButton.setActionCommand("cookie");
//		cookieButton.setContentAreaFilled(false);
		cookiePanel.add(cookieButton);
		
		JPanel counterPanel = new JPanel();
		counterPanel.setBounds(100, 100, 200, 100);
		counterPanel.setBackground(Color.black);
		counterPanel.setLayout(new GridLayout(2,1));
		window.add(counterPanel);
		
		counterLabel = new JLabel(cookieCounter + " cookies");
		counterLabel.setForeground(Color.white);
		counterLabel.setFont(font1);
		counterPanel.add(counterLabel);
		
		perSecLabel = new JLabel();
		perSecLabel.setForeground(Color.white);
		perSecLabel.setFont(font2);
		counterPanel.add(perSecLabel);
		
		JPanel itemPanel = new JPanel();
		itemPanel.setBounds(500, 170, 250, 250);
		itemPanel.setBackground(Color.black);
		itemPanel.setLayout(new GridLayout(4,1));
		window.add(itemPanel);
		
		button1 = new JButton("Cursor");
		button1.setFont(font1);
		button1.setFocusPainted(false);
		button1.addActionListener(cHandler);
		button1.setActionCommand("Cursor");
		button1.addMouseListener(mHandler);
		itemPanel.add(button1);
		button2 = new JButton("?");
		button2.setFont(font1);
		button2.setFocusPainted(false);
		button2.addActionListener(cHandler);
		button2.setActionCommand("Grandpa");
		button2.addMouseListener(mHandler);
		itemPanel.add(button2);
		button3 = new JButton("?");
		button3.setFont(font1);
		button3.setFocusPainted(false);
		button3.addActionListener(cHandler);
		button3.setActionCommand("");
		button3.addMouseListener(mHandler);
		itemPanel.add(button3);
		button4 = new JButton("?");
		button4.setFont(font1);
		button4.setFocusPainted(false);
		button4.addActionListener(cHandler);
		button4.setActionCommand("");
		button4.addMouseListener(mHandler);
		itemPanel.add(button4);
		
		JPanel messagePanel = new JPanel();
		messagePanel.setBounds(500, 70, 250, 150);
		messagePanel.setBackground(Color.black);
		window.add(messagePanel);
		
		messageText = new JTextArea();
		messageText.setBounds(500, 70, 250, 150);
		messageText.setForeground(Color.white);
		messageText.setBackground(Color.black);
		messageText.setFont(font2);
		messageText.setLineWrap(true);
		messageText.setWrapStyleWord(true);
		messageText.setEditable(false);
		messagePanel.add(messageText);
		
		window.setVisible(true);
	}
	public void setTimer(){
		
		timer = new Timer(timerSpeed, new ActionListener(){
			
			@Override
			public void actionPerformed(ActionEvent e){
				
				cookieCounter++;
				counterLabel.setText(cookieCounter + " cookies");
				
				if(grandpaUnlocked==false){
					if(cookieCounter>=100){
						grandpaUnlocked=true;
						button2.setText("Grandpa " + "(" + grandpaNumber + ")");
					}
				}
			}
		});
	}
	public void timerUpdate(){
		
		if(timerOn==false){
			timerOn=true;
		}
		else if(timerOn==true){
			timer.stop();
		}
		
		double speed = 1/perSecond*1000;
		timerSpeed = (int)Math.round(speed);
		
		String s = String.format("%.1f", perSecond);
		perSecLabel.setText("per second: " + s);
		
		setTimer();
		timer.start();
	}
	
	
	public class CookieHandler implements ActionListener{
		
		public void actionPerformed(ActionEvent event){
			
			String action = event.getActionCommand();
			
			switch(action){
			case "cookie":
				cookieCounter++;
				counterLabel.setText(cookieCounter + " cookies");
				break;
			case "Cursor":
				if(cookieCounter>=cursorPrice){
					cookieCounter = cookieCounter - cursorPrice;
					cursorPrice = cursorPrice + 5;
					counterLabel.setText(cookieCounter + " cookies");
					
					cursorNumber++;
					button1.setText("Cursor " + "(" + cursorNumber + ")");
					messageText.setText("Cursor\n[price: " + cursorPrice + "]\nAutoclicks once every 10 seconds.");
					perSecond = perSecond + 0.1;
					timerUpdate();
				}
				else{
					messageText.setText("You need more cookies!");
				}
				break;
			case "Grandpa":
				if(cookieCounter>=grandpaPrice){
					cookieCounter = cookieCounter - grandpaPrice;
					grandpaPrice = grandpaPrice + 50;
					counterLabel.setText(cookieCounter + " cookies");
					
					grandpaNumber++;
					button2.setText("Grandpa " + "(" + grandpaNumber + ")");
					messageText.setText("Grandpa\n[price: " + grandpaPrice + "]\nEach grandpa produces 1 cookie per second.");
					perSecond = perSecond + 1;
					timerUpdate();
				}
				else{
					messageText.setText("You need more cookies!");
				}
				break;
				
			}
			
		}
	}
	
	public class MouseHandler implements MouseListener{
		
		@Override
		public void mouseClicked(MouseEvent e){
			
		}
		@Override
		public void mousePressed(MouseEvent e){
			
		}
		@Override
		public void mouseReleased(MouseEvent e){
			
		}
		@Override
		public void mouseEntered(MouseEvent e){
			
			JButton button = (JButton)e.getSource();
			
			if(button == button1){
				messageText.setText("Cursor\n[price: " + cursorPrice + "]\nAutoclicks once every 10 seconds.");
			}
			else if(button == button2){
				if(grandpaUnlocked==false){
					messageText.setText("This item is currently locked!");
				}
				else{
					messageText.setText("Grandpa\n[price: " + grandpaPrice + "]\nEach grandpa produces 1 cookie per second.");
				}
				
			}
			else if(button == button3){
				messageText.setText("This item is currently locked!");
			}
			else if(button == button4){
				messageText.setText("This item is currently locked!");
			}
		}
		@Override
		public void mouseExited(MouseEvent e){
			
			JButton button = (JButton)e.getSource();
			
			if(button == button1){
				messageText.setText(null);
			}
			else if(button == button2){
				messageText.setText(null);
			}
			else if(button == button3){
				messageText.setText(null);
			}
			else if(button == button4){
				messageText.setText(null);
			}
		}
	}	
}



end

[Java Code Sample] Create timer (normal/countdown/two digits)

 

Here's a sample code to create various timers.


In this code, we make three kinds of timer.

1. Simple timer

2. Normal timer (Like stopwatch)

3. Countdown timer 


Please check my video tutorial if you want to follow the process step by step:



Here's the code:



import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

public class Main {
	
	JFrame window;
	JLabel counterLabel;
	Font font1 = new Font("Arial", Font.PLAIN, 70);	
	Timer timer;	
	int second, minute;
	String ddSecond, ddMinute;	
	DecimalFormat dFormat = new DecimalFormat("00");
	

	public static void main(String[] args) {
		
		new Main();		
	}
	
	public Main() {
		
		window = new JFrame();
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.setLayout(null);
		
		counterLabel = new JLabel("");
		counterLabel.setBounds(300, 230, 200, 100);
		counterLabel.setHorizontalAlignment(JLabel.CENTER);
		counterLabel.setFont(font1);
		
		window.add(counterLabel);
		window.setVisible(true);
		
// Enable this to use Simple Timer
//		second = 0;
//		simpleTimer();
//		timer.start();
		
// Enable this to use Normal Timer
//		counterLabel.setText("00:00");
//		second =0;
//		minute =0;
//		normalTimer();
//		timer.start();
		
		// Countdown Timer
		counterLabel.setText("03:00");
		second =0;
		minute =3;
		countdownTimer();
		timer.start();						
	}
    
// Enable this to use Simple Timer
//	public void simpleTimer() {
//		
//		timer = new Timer(1000, new ActionListener() {
//			
//			@Override
//			public void actionPerformed(ActionEvent e) {
//				
//				second++;
//				
//				counterLabel.setText(""+ second);
//			}
//		});
//	}
	
// Enable this to use Normal Timer
//	public void normalTimer() {
//		
//		timer = new Timer(1000, new ActionListener() {
//			
//			@Override
//			public void actionPerformed(ActionEvent e) {
//				
//				second++;
//				
//				ddSecond = dFormat.format(second);
//				ddMinute = dFormat.format(minute);				
//				counterLabel.setText(ddMinute + ":" + ddSecond);
//				
//				if(second==60) {
//					second=0;
//					minute++;
//					
//					ddSecond = dFormat.format(second);
//					ddMinute = dFormat.format(minute);
//					counterLabel.setText(ddMinute + ":" + ddSecond);
//				}
//			}
//		});
//	}
	public void countdownTimer() {
		
		timer = new Timer(1000, new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				
				second--;
				ddSecond = dFormat.format(second);
				ddMinute = dFormat.format(minute);	
				counterLabel.setText(ddMinute + ":" + ddSecond);
				
				if(second==-1) {
					second = 59;
					minute--;
					ddSecond = dFormat.format(second);
					ddMinute = dFormat.format(minute);	
					counterLabel.setText(ddMinute + ":" + ddSecond);
				}
				if(minute==0 && second==0) {
					timer.stop();
				}
			}
		});		
	}		
}




Result:



[Java Code Sample] Create color chooser panel


Here's a code to display a color palette panel so you can select a color and apply it to your object.


Video tutorial:


Code:


import java.awt.Color;
import javax.swing.JColorChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class Main implements ChangeListener{
	
	JFrame window;
	JColorChooser cc;
	JPanel colorChooserPanel, colorPanel;

	public static void main(String[] args) {
		
		new Main();

	}
	
	public Main(){
		
		window = new JFrame();
		window.setSize(800, 600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		window.setLayout(null);
		
		colorChooserPanel = new JPanel();
		colorChooserPanel.setBounds(100, 50, 600, 350);
		colorChooserPanel.setBackground(Color.black);
		window.add(colorChooserPanel);
		
		cc = new JColorChooser();
		cc.getSelectionModel().addChangeListener(this);
		
		// to remove preview panel
		cc.setPreviewPanel(new JPanel());
		
		// to remove the panes
//		cc.removeChooserPanel(cc.getChooserPanels()[4]); // CMYK
//		cc.removeChooserPanel(cc.getChooserPanels()[3]); // RGB
//		cc.removeChooserPanel(cc.getChooserPanels()[2]); // HSL
//		cc.removeChooserPanel(cc.getChooserPanels()[1]); // HSV
//		cc.removeChooserPanel(cc.getChooserPanels()[0]); // Swatch
		
		colorChooserPanel.add(cc);
		
		colorPanel = new JPanel();
		colorPanel.setBounds(200, 420, 400, 100);
		colorPanel.setBackground(Color.white);
		window.add(colorPanel);
			
		window.setVisible(true);
	}
	
	public void stateChanged(ChangeEvent e){
		
		Color newColor = cc.getColor();
		colorPanel.setBackground(newColor);
	}	
}






Result



[Java Code Sample] How to use RGB color

 

Here's a sample code to use RGB color for objects:


Video tutorial:



Code:


import java.awt.Color;
import javax.swing.JButton;
import javax.swing.JFrame;

public class Main {
	
	JFrame window;
	JButton button;

	public static void main(String[] args) {
		
		new Main();

	}
	public Main(){
		
		window = new JFrame();
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		window.setLayout(null);
		window.setVisible(true);
				
		button = new JButton();
		button.setBounds(250, 250, 300, 100);
        // Type RGB color code
		button.setBackground(new Color(127,55,34));
		window.add(button);
	}
}


Here's the result:


The button background is painted by the specified RGB color (127,55,34)

[Java Code Sample] How to display text letter by letter on JTextArea

 

Just like some old school RPGs or adventure games, here’s how to display text letter by letter in Java.

Here's the video tutorial:



And here's the code:


import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.Timer;
 
public class Main {
     
    JFrame window;
    JPanel textPanel;
    JTextArea textArea;
    Font normalFont = new Font("Times New Roman", Font.PLAIN, 28);
     
    String text;
    int i =0;
     
    Timer timer = new Timer(80, new ActionListener(){
        @Override
        public void actionPerformed(ActionEvent e){
             
            char character[] = text.toCharArray();
            int arrayNumber = character.length;
             
            String s = String.valueOf(character[i]);
             
            textArea.append(s);
             
            i++;
     
            if(i == arrayNumber){
                i = 0;
                timer.stop();
            }
        }       
    });
     
 
    public static void main(String[] args) {
         
        new Main ();
    }
     
    public Main(){
         
        window = new JFrame();
        window.setSize(800, 600);
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.getContentPane().setBackground(Color.black);
        window.setLayout(null);
         
        textPanel = new JPanel();
        textPanel.setBounds(100, 100, 600, 250);
        textPanel.setBackground(Color.black);
        window.add(textPanel);
         
        textArea = new JTextArea();
        textArea.setBounds(100, 100, 600, 250);
        textArea.setBackground(Color.black);
        textArea.setForeground(Color.white);
        textArea.setFont(normalFont);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        textPanel.add(textArea);
         
        window.setVisible(true);
         
        text = "This is the text area. This game is going to be great. I'm sure of it!!!!!!!!!!";
         
        timer.start();
    }
}

end

[Java Code Sample] How to use a custom font

 Here's the sample code to use a custom font in Java:

*Prepare ttf font and put it in your project folder



package p1;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.IOException;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {
	
	JFrame window;
	JPanel textPanel;
	JLabel textLabel;
	Font normalFont = new Font("Times New Roman", Font.PLAIN, 28);
	Font pixelMplus;

	public static void main(String[] args) {

		new Main();
	}
	
	public Main(){
		
		try{
            // load a custom font in your project folder
			pixelMplus = Font.createFont(Font.TRUETYPE_FONT, new File("yourFontName.ttf")).deriveFont(30f);	
			GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
			ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, new File("yourFontName.ttf")));			
		}
		catch(IOException | FontFormatException e){
			
		}
						
		window = new JFrame();
		window.setSize(800,600);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.getContentPane().setBackground(Color.black);
		window.setLayout(null);
		
		textPanel = new JPanel();
		textPanel.setBounds(100, 250, 600, 250);
		textPanel.setBackground(Color.black);
		
		textLabel = new JLabel("Hello traveler!");
		textLabel.setBackground(Color.black);
		textLabel.setForeground(Color.white);
		textLabel.setFont(pixelMplus);
		textPanel.add(textLabel);
		
		window.add(textPanel);
		
		window.setVisible(true);		
	}
}

Result:


(I used a font called "PixelMplus10-Regular")


Here's my video tutorial: