Archive for July, 2010

Changing the colour of a JButton on ‘mouse hover’

July 23, 2010 2 comments

While working on i project my UI conscious client wanted that the buttons(JButton) changes its colour when the mouse is hovered over it.
Then i wrote this custom version of JButton, the ‘PosButton’ that create a button whose default color and mouse over colour can be specified at the time of object creation i.e. new PosButton(String text, Color defaultColor, Color ouseOverColor)….
I felt that this code can be useful
for many, so i am posting it….

to use the code just copy it and save in a file named, and use this custom button. Here goes the code:

import javax.swing.JButton;
import java.awt.Color;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;

public class PosButton extends JButton implements MouseListener { 

//instance variables

private Color defaultColor;
private Color mouseOverColor;

//class constructor

public PosButton(String text, Color defaultColor, Color mouseOverColor) { 



this.defaultColor = defaultColor;

this.mouseOverColor = mouseOverColor;



//override the methods of implemented MouseListener

public void mouseClicked(MouseEvent e) { }

public void mousePressed(MouseEvent e) { }

public void mouseReleased(MouseEvent e) { }

public void mouseEntered(MouseEvent e) { 

if(e.getSource()==this) {  this.setBackground(this.mouseOverColor); }


public void mouseExited(MouseEvent e) { 

if(e.getSource()==this) { this.setBackground(this.defaultColor); }



And to test the PosButton, here’s

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

public class MyFrame extends JFrame {

//instance attributes

private PosButton pb;

//class constructor

public MyFrame() {

super("Button colour change demo");

setLayout(new FlowLayout());


//instantiate PosButton class

pb = new PosButton("Button by Hassan", new Color(255, 125, 64), new Color(192, 255, 62));




//main method

public static void main(String[] args) { 

MyFrame mf = new MyFrame();



Categories: Java

HangMan in Java

July 22, 2010 3 comments

Here’s s simple version of HangMan, that i completed yesterday. It has a GameLogicEngine class containing its core rules. If any of you find any sort of suggestions to improve it than please do let me know by commenting the post…

The following class the is responsible for the GUI display logic and interfacing with players.

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

public class HangManGUI extends JFrame implements ActionListener { 

//instance variables

private JMenuBar jMenuBar;

private JMenu helpMenu, exitMenu;

private JMenuItem aboutMenuItem;

private JPanel leftPanel, rightPanel, centerPanel;

private JButton[] abcButtons;

private JButton newWordButton;

private JLabel wordLabel, imageLabel;

public GameLogicEngine gle;

private static String[] abc = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

public static Character[] insertLetter;

private static String[] imgNames = {"imgs/hm_1.png", "imgs/hm_2.png", "imgs/hm_3.png", "imgs/hm_4.png", "imgs/hm_5.png", "imgs/hm_6.png", "imgs/hm_7.png", "imgs/hm_8.png", "imgs/hm_9.png", "imgs/hm_10.png"};

private int hangManState = 0;

//**class constructor**//

public HangManGUI() {

super("HangMan - Beta Version (0.0)");

this.setSize(400, 400);



//instantiate the JMenuBar and add it to the JFrame object

this.jMenuBar = new JMenuBar();

this.helpMenu = new JMenu("Help");

this.aboutMenuItem = new JMenuItem("About");




this.exitMenu = new JMenu("Exit");




this.setLayout(new BorderLayout());

//instantiate the GameLogicEngine class = new GameLogicEngine();


//this method is responsible for painting all the components on the JFrame object

public void pasteComponents() { 

this.leftPanel = new JPanel();

this.leftPanel.setPreferredSize(new Dimension(120, 400));


this.add(this.leftPanel, BorderLayout.WEST);

//instantiate the JButton array

this.abcButtons = new JButton[26];

for(int i=0; i<26; i++) { 

this.abcButtons[i] = new JButton([i]);




//instantiate the JButton instance "newWordButton"

this.newWordButton = new JButton("New Word");


this.newWordButton.setFont(new Font("Times New Roman", Font.BOLD, 12));

this.add(newWordButton, BorderLayout.SOUTH);

//instantiate the JPanel rightPanel

this.rightPanel = new JPanel();
this.rightPanel.setPreferredSize(new Dimension(270, 400));

this.add(this.rightPanel, BorderLayout.EAST);

//add image to the rightPanel object

this.imageLabel = new JLabel();

this.imageLabel.setIcon(new ImageIcon(HangManGUI.imgNames[0]));


//instantiate the centerPanel

this.centerPanel = new JPanel();
this.centerPanel.setPreferredSize(new Dimension(40, 50));

//instantiate the wordLabel
this.wordLabel = new JLabel("         A word will appear here");
this.wordLabel.setFont(new Font("Courier New Bold", Font.BOLD, 17));

this.centerPanel.setLayout(new BorderLayout());
this.centerPanel.add(this.wordLabel, BorderLayout.CENTER);

this.add(this.centerPanel, BorderLayout.CENTER);


//a mthod responsible for replacing a new word on the GUI when the newWordButton is pressed

private void pasteNewWord(String word) { 

String displayWord = " ";

for(int i=0; i<word.length(); i++) { 

displayWord+=" _ ";




//this method is responsible for the displaying of the correct word pressed by player

public void displayCorrectLetter() { 

String displayLetter = " ";

for(int i=0; i<HangManGUI.insertLetter.length; i++) { 

if(HangManGUI.insertLetter[i]!=null) {

displayLetter+= " "+HangManGUI.insertLetter[i].toString()+" ";

else { 

displayLetter+=" _ ";





//override actionPerformed()

public void actionPerformed(ActionEvent ev) { 

//check first for events from (A-Z) abcButtons

for(int i=0; i<26; i++) { 

if(ev.getSource()==this.abcButtons[i]) { = this.abcButtons[i].getText();

System.out.println("You Pressed: ";

//**problematic code possibly begins here

if( { 



for(int j=0; j<HangManGUI.insertLetter.length; j++) { 




else { 

System.out.println("I am else");

this.imageLabel.setIcon(new ImageIcon(HangManGUI.imgNames[this.hangManState])); 




if(ev.getSource()==this.aboutMenuItem) { 

ApplicationDialog ad = new ApplicationDialog(this, "About");



else { 

if(ev.getSource()==this.exitMenu) { System.exit(0); }

else { 

if(ev.getSource()==this.newWordButton) { 

String word = WordRepository.generateWord();

HangManGUI.insertLetter = new Character[word.length()]; = word;



System.out.println("Random Word Generated is: "+ word);






The following class is basically a word repository for the HangMan and is responsible for the word generation at random.

import java.util.*;

public class WordRepository { 

//static variables

private static String[] words = {"FRUIT", "USMAN", "FISH", "WATER", "PAKISTAN", "PLANET", "CLOUDS", "COMPUTER", "VENUS", "OCEAN"};

//a method that generates a word at random

public static String generateWord() { 

//instantiate the Random class and invoke the nextInt() method to generate a randome number

Random ran = new Random();

int wordIndex = ran.nextInt(WordRepository.words.length);

String selectedWord = WordRepository.words[wordIndex];

return selectedWord;



This class the is particularly the most important one controlling and defining the game’s logic

 * The core functionality of this class
 * is to embed the Basic Logic of HangMan.
 * It is kept final so it may not be extended 
 * and customized therefore.

public final class GameLogicEngine { 

//instance variable

String randomWordGenerated;

String presentWordPressed;

private int matchingIndex;

// a method to evaluate the decision of player in the pressing of letters(A-Z) for
// filling the missing letters of the word displayed, this method returns a 1 for correcyt letter
//selection by user and a 0 for the incorrect

public int evaluateDecision() { 

int result=0;

if( this.checkLetterPresence() ) { 

for(int i=0; i<this.randomWordGenerated.length(); i++) { 

if(i==this.matchingIndex) { 

result = 1;

HangManGUI.insertLetter[i] = this.presentWordPressed.charAt(0);




else { 

result = 0;


return result;

//a method to check weather the pressed letter is contained in the randomly generated word or not

private boolean checkLetterPresence() { 

boolean retBool;

int val = this.randomWordGenerated.indexOf(this.presentWordPressed);

if((val!=-1)&(val<=(this.randomWordGenerated.length()-1))) {

this.matchingIndex = val;

retBool = true;


else { 

retBool = false;


return retBool;



The following class is for presenting Application specific dialogs and is a custom version of the JDialog.

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

public class ApplicationDialog extends JDialog implements ActionListener { 

private JLabel aboutLabel;

private JButton okButton;

//**class constructor**//

public ApplicationDialog(JFrame ownerFrame, String title) { 

//invoke the parent class constructor

super(ownerFrame, true);


setSize(400, 400);

setLocation(270, 150);

setLayout(new FlowLayout());


///////below would be methods that are responsible for displaying content on the/////////////
//////JDialog object as per event requirememnts//////////////////////////////////

public void showAbout() {

add(new JLabel("          "));

aboutLabel = new JLabel(new ImageIcon("imgs/hello.gif"));


add(new JLabel("                                                                             "));

add(new JLabel("Software developed by:   Hassan Ali BS(CS) 6A"));

okButton = new JButton("OK");




//override actionPerformed()

public void actionPerformed(ActionEvent event) { 

if(event.getSource()==okButton) { 





Last but not least this is the Driver for main:-)

public class Driver { 

public static void main(String[] args) { 

HangManGUI hg = new HangManGUI();




You can make comments on the post directly at the page or can also mail me at


Categories: Java

Java the Object – Oriented!!

July 15, 2010 Leave a comment

After a lots of years of the Structural Programming the world is now shifting towards the component based methodology. Yes! the object oriented approach. Design and develop the software in components or objects. Infact it is a great approach interms of reusebility, maintenance, development and testing. With many OO technologies on the scene, Java is very widely used. The reason is that its purely OO. Java provides a very good base for OO developmet in terms of classes, interfaces, abstract classes. So by days, many OO programmers are switching to Java.

Categories: Java