Hi,

I am building a game in which i have used array for applying 52 button, which works fine.But when i try to use Action Listener with the array of button and try use setEnable(false)or true it does not work.I am also sending my.

import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.*;

public class tasking extends JFrame implements ActionListener{

	JMenuBar mb;
	JMenu file,help;
	JMenuItem newgame,exit,about,rules;
	JButton b1[];
	JPanel p1,p2;
	int z,i,a,count=1;
	String text;
	ImageIcon as[];
	JLabel score,time;
	boolean bl,bl2;
	public tasking(){
		
		mb=new JMenuBar();
		setJMenuBar(mb);
		file=new JMenu("File");
		newgame=new JMenuItem("New Game");
		exit=new JMenuItem("Exit");
		mb.add(file);
		file.add(newgame);
		file.add(exit);
		newgame.addActionListener(this);
		exit.addActionListener(this);
		help=new JMenu("Help");
		about=new JMenuItem("About");
		rules=new JMenuItem("Game Rules");
		mb.add(help);
		help.add(rules);
		help.add(about);
		
		p1=new JPanel();
		ImageIcon as[]=new ImageIcon[52];
		JButton b1[]=new JButton[52];
		p1.setLayout(new GridLayout(4,2,5,5));
		for(int i=0;i<b1.length;i++){
		as[i]=new ImageIcon("D:/WorkSpace/images.gif");
		b1[i]=new JButton(as[i]);
		b1[i].addActionListener(this);
		b1[i].setEnabled(false);
		p1.add(b1[i]);
		}
		
		p2=new JPanel();
		p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
		score=new JLabel("Your Score:      ");
		time=new JLabel("Timer:            ");
		p2.add(score);
		p2.add(time);
		
		Container c1=getContentPane();
		c1.setLayout(new BorderLayout());
		c1.add(p1,BorderLayout.CENTER);
		c1.add(p2,BorderLayout.SOUTH);
	}
				
	/**
	 * This method initializes this
	 * 
	 */
	
	public void actionPerformed(ActionEvent e){
		
		if(e.getSource().equals(exit)){
			System.exit(0);
		}
		
		if(e.getSource().equals(newgame)){
			try{
			JButton b1[]=new JButton[52];
				b1[i]=new JButton();
			
			    b1[i].setEnabled(true);
			    bl=b1[i].isEnabled();
			    System.out.println("Status:"+bl);
				newgame.setEnabled(false);
										
			}catch(Exception ex){
				System.err.println("Exception occurred :" + ex.toString());
				ex.printStackTrace();
			}
			
			Thread t=new Thread(){
				 public void run(){
					 
				for(a=1; a<=30; a++)
				{
					time.setText("Timer: "+ count);
					count++;
					if(a==30){
						count=1;
						newgame.setEnabled(true);
					JButton b1[]=new JButton[52];
					b1[i]=new JButton();
					b1[i].setEnabled(false);
					
					}
				      
					try{
						repaint();
						Thread.sleep(500);
				}
					 catch(InterruptedException e)
					 {}
				}
				 }				
				} ;
				t.start();	
		}	
	}
		  /**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
         tasking ta=new tasking();
         ta.setTitle("Multithreding");
         ta.setSize(700,700);
         ta.setVisible(true);
	}

}

it does not work

When you have errors, please copy and paste the full text of the message here.
It saves lots of time figuring out what does not work

Hi.
At first glance it seem that the array b1 is declared many times:
in the class

JButton b1[];

.
in the default constructor.

JButton b1[]=new JButton[52];

in the actionPerformed method:

JButton b1[]=new JButton[52];

and in the run method

JButton b1[]=new JButton[52];

Please try to avoid this multiple declarations

Hope it helps.

Hi,

Thanks for the advice. Well I have made some changes in my code as per your recommendation. But it do not seem to work and had started giving NullPointerExeption.I have posted my new code and complete stack trace.

import javax.swing.*;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import java.awt.event.*;

public class arraytest1 {

	JButton jButton[],b2;
	private int count=0;
	int i,z;
	String tl;
	JPanel p1;
	public arraytest1(){
		
		JFrame jframe = new JFrame();
		p1=new JPanel();
		JButton jButton[]=new JButton[4];
		p1.setLayout(new GridLayout(4,2,5,5));
		for(int i=0;i<jButton.length;i++){
		jButton[i] = new JButton(new ImageIcon("D:/WorkSpace/images.gif"));
		jButton[i].addActionListener(new NewListener());
		p1.add(jButton[i]);
		}
		
		  jframe.add(p1);
		  jframe.pack();
	      jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	      jframe.setVisible(true);
	      count++;
	      
	      
	}
	private class NewListener implements ActionListener
	
	{
	/* (non-Javadoc)
	* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		public void actionPerformed(ActionEvent e){
						
			try{
								
			if(count==1)
			{
				System.out.println("Value:" +count);
							
		jButton[i].setIcon(new ImageIcon("D:/WorkSpace/cards/as.gif"));
				
			}
			
			if (count==2)
			{
				System.out.println("Value:" +count);
					
		jButton[i].setIcon(new ImageIcon("D:/workSpace/cards/ac.gif"));
				
			}
			
			if(count==3)
			{
			   System.out.println("Value:"+count);
			   				
		   jButton[i].setIcon(new ImageIcon("D:/WorkSpace/cards/ad.gif"));
			}
			
			if(count==4)
			{
				System.out.println("Value:"+count);
								
		jButton[i].setIcon(new ImageIcon("D:/workSpace/cards/ah.gif"));
			}
			 }catch(Exception ex){
		System.err.println("Exception occurred :"+ex.toString());
		ex.printStackTrace();
				}
			 count++;
			 			 
			 }
	}
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		
		new arraytest1();
		// TODO Auto-generated method stub

	}

	}

Stack Trace
Exception occurred :java.lang.NullPointerException
java.lang.NullPointerException
at arraytest1$NewListener.actionPerformed(arraytest1.java:51)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Hi.
At first glance it seem that the array b1 is declared many times:
in the class .
in the default constructor.

JButton b1[]=new JButton[52];

in the actionPerformed method:

JButton b1[]=new JButton[52];

and in the run method

JButton b1[]=new JButton[52];

Please try to avoid this multiple declarations

Hope it helps.

Do you know what a NullPointerException means?
have you looked at line 51 in your code to see if there could be a null "pointer" there?
Java doesnt' talk about pointers except somehow they left it in the error message.
Java has variables that refer to objects. Pointers in C.
The array entry on line 51 must be null, not a reference to some object.
So the question is: Why is that entry null?
Add some debugging code to see what is put in the array at each location and what is the value of i when the NPE occurs.

JButton jButton[]=new JButton[4];

You've create a whole new object here. The one at the class level is still empty.

Edited 6 Years Ago by NormR1: n/a

Hi
You still have two time declatation of jButton array: one at the class level; as NormR1 said; and the other inside the constructor.
may be you need to modify this :

JButton jButton[]=new JButton[4];

to:

jButton[]=new JButton[4];

Hope it helps.

Hi,

Thanks a lot the changes you have ask me to do worked and now I am able to change ImageIcon on the button. But there is another issue which has come up. When I press the first button the image do change but when I click any other of the three buttons there image does not changes but image of the first button do get replaced by the image of the button I have clicked.

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

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.util.*;

public class arraytest1 {

	JButton jButton[],b2;
	int count=0;
	int i,z;
	String tl;
	JPanel p1;
		
	public arraytest1(){
		
		JFrame jframe = new JFrame();
		p1=new JPanel();
		jButton=new JButton[4];
		p1.setLayout(new GridLayout(4,2,5,5));
		for(int i=0;i<jButton.length;i++){
jButton[i] = new JButton(Integer.toString(i+1),new ImageIcon("D:/WorkSpace/images.gif"));
		jButton[i].addActionListener(new NewListener());
		p1.add(jButton[i]);
		
		
		}
		
		  jframe.add(p1);
		  jframe.pack();
	      jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	      jframe.setVisible(true);
	      
	     	      
	      
	}
	private class NewListener implements ActionListener
	
	{
		/* (non-Javadoc)
		 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
		 */
		public void actionPerformed(ActionEvent e){
						
			try{
				String tl=((JButton)e.getSource()).getText();
				System.out.println("Value of text " + tl);
				z=Integer.parseInt(tl);
			
				if(z==1)
			   {
				System.out.println("Value:" +z);
				
		jButton[i].setIcon(new ImageIcon("D:/WorkSpace/cards/as.gif"));
				
				}	
					
			else if(z==2)
			{
				System.out.println("Value:" +z);
					
		jButton[i].setIcon(new ImageIcon("D:/workSpace/cards/ac.gif"));
				
			}
			
						
			else if(z==3)
			{		
			   System.out.println("Value:"+z);
		   jButton[i].setIcon(new ImageIcon("D:/WorkSpace/cards/ad.gif"));
			   
			}
			
			else if(z==4)
			{
			
				System.out.println("Value:"+z);
		jButton[i].setIcon(new ImageIcon("D:/workSpace/cards/ah.gif"));
					
			}
						 
			}catch(Exception ex){
			System.err.println("Exception occurred :"+ex.toString());
					ex.printStackTrace();
				}
			
			 	}
			
	}
	/**
	 * @param args
	 */
	public static void main(String[] args)
	{
		
		new arraytest1();
		// TODO Auto-generated method stub

	}

	}

Hi
You still have two time declatation of jButton array: one at the class level; as NormR1 said; and the other inside the constructor.
may be you need to modify this :

JButton jButton[]=new JButton[4];

to:

jButton[]=new JButton[4];

Hope it helps.

Try debugging your program some more by displaying the value of i when you are using it as an index to the jbutton[] array. Does it have the value you expect? You display the value of z but i is the index to the array

Just change code in actionPerformed() method from

jButton[i].setIcon(...)

to

jButton[z-1].setIcon(...)

The reason is that you are using 'i' as index and now 'i' value is the length of JButton objects. You picked the value from the button, but not use it in your call. Also, it has to be z-1 because the number (text) displayed on the button has already been increased by 1 when you created it.

Edited 6 Years Ago by Taywin: n/a

Hi,

But there is another issue which has come up. When I press the first button the image do change but when I click any other of the three buttons there image does not changes but image of the first button do get replaced by the image of the button I have clicked.

This is because the value of "i" is "0" (zero) and not the length of jButton.

Oh... Weird behavior in Java... Didn't see that 'i' was declared on the top without being initiated. Then the 'i' was declared again and used inside 'for' loop. The outside scope of 'i' is still there and should be affected. It should not be equal to 0??? The compiler should catch it instead of let this pass???

By the way, if anyone is going to say that because 'i' is primitive and cannot be null but is assigned to 0 by default, I do not believe it. I have written a very simple code to test that and the compiler still complain that 'i' has not been initialized.

Edited 6 Years Ago by Taywin: n/a

compiler still complain that 'i' has not been initialized.

That's a compile time error. NPE is an execution error.
I think the reason might be that the compiler does not generate initialization code for local variables, so they can have whatever is left over in memory.

If I understand what the code have to do:

A- Initialy

1-All the buttons have at the beganing the icon "images.gif"
2-We initialize The value of "i" to -1 (i=-1).


B-The first time the user clik on one of the buttons:
1- z (z=Integer.parseInt(tl)-1) holds the index of the jButon wich the user clicked on (jButton[z]);
2- change the icon of the jButton[z] to some icon "xxxx.gif"
3-The value of variable "i" holds the index of the cliked button (i=z).

C-The second and the Nth time the user clik on one of the buttons:
1- z (z=Integer.parseInt(tl)-1) holds the index of the jButon wich the user clicked on (jButton[z]);
2- change the icon of the jButton[z] to some icon "xxxx.gif"
3- change the icon of the jButton to the icon "images.gif"
4-The value of variable "i" holds the index of the cliked button (i=z).

Issues:
a-What if the user clik on the same button he cloked previousaly?
Is its icon must be changed to "images.gif" or left inchanged?
This will cause some change in the step C above.

b-How to retreive the "xxxx.gif"?
This will be more convinient if you put all the icons in some array as you did with the jButton, some kind of:

Icon[] icones=new Icon[4];
//and then initialize it
icones[0]=new ImageIcon("...");
//and so on

and in the actionPerformed:

//if we have to change the icon of the cliked button (in B-2 and C-2 above):
jButton[z].setIcon(icones[z]);

The benicite is to avoid the multiple "if else".

Hope it helps

That's a compile time error. NPE is an execution error.

NPE would occur if and only if it recognizes that 'i' has already been initialized. In this case, it should be caught at compile time because 'i' has never been initialized within its scope.

NPE would occur if and only if it recognizes that 'i' has already been initialized

That doesn't make any sense.
You get a NPE when you use a reference/(pointer to an object) that has a null value. i is not a reference variable, its a primitive: int.
I have no idea who "recognizes" the state of variables. Who it the "it" that is doing the recognizing?

In fact this is not the issue of this thread but here is some notes:

By the way, if anyone is going to say that because 'i' is primitive and cannot be null but is assigned to 0 by default, I do not believe it. I have written a very simple code to test that and the compiler still complain that 'i' has not been initialized.

Beleive or not "For type int, the default value is zero, that is, 0."
this phrase is extracted from the java specification language.
And please show me the code you wrote.

and so

I think the reason might be that the compiler does not generate initialization code for local variables, so they can have whatever is left over in memory

The int variable is effectively initialized to Zero not to "whatever is left over in memory".


And

the NullPointerException is "Thrown when an application attempts to use null in a case where an object is required"

this is what the javaDoc said about the NPE.
The emphasis here is on "object".
And the only Variables of Reference Type can hold the null value.
Please get back to the thread's topic.

Hope it helps.

Who it the "it" that is doing the recognizing?

It is the compiler, sorry.

And please show me the code you wrote.

Try this please...

public class ABC() {
  public static void main(String[] args) {
    int a;
    System.out.println(a);
  }
}

If a by default is 0, you should be able to print 'a', but you will actually can't pass the compiler because it will complain. I use command line to compile it by the way. Not use IDE.

Edited 6 Years Ago by Taywin: n/a

Hi,
This is because the variable "a" is a local variable and the specification stipule that:
the Java programming language does not automatically
initialize local variables in order to avoid masking programming errors.

This sentence is extracted one more time from the specification.
The following code give print 0 to the output put.

public class ABC{
int a;
public void Test(){
 System.out.println(a);
}
public static void main(String[] args){

new ABC().Test();
}
}

But please get back to the thread because OP is not asking for that..

Hi,

Thanks a lot, you were right the value of i was 0 and have been able to fix the issue. Now I am facing a problem with my MenuItem as it through java.lang.ClassCastException. Which seems to be happening because of String text=((JButton)e.getSource()).getText();.My code and stack trace is given below.

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

import java.util.*;

public class cardgame extends JFrame implements ActionListener{

	JMenuBar mb;
	JMenu file,help;
	JMenuItem newgame,exit,about,rules;
	JButton b1[];
	JPanel p1,p2;
int z, i, a,   count=1,count1=0,count2,count3,count4,count5,count6,count7,count8,count9,count10,count11,count12,count13;
	String text;
	ImageIcon as[];
	JLabel score,time;
	boolean bl,bl2;
	char choice;
	public cardgame(){
		
		mb=new JMenuBar();
		setJMenuBar(mb);
		file=new JMenu("File");
		newgame=new JMenuItem("New Game");
		exit=new JMenuItem("Exit");
		mb.add(file);
		file.add(newgame);
		file.add(exit);
		newgame.addActionListener(this);
		exit.addActionListener(this);
		help=new JMenu("Help");
		about=new JMenuItem("About");
		rules=new JMenuItem("Game Rules");
		mb.add(help);
		help.add(rules);
		help.add(about);
		
		p1=new JPanel();
		b1=new JButton[52];
		p1.setLayout(new GridLayout(4,2,5,5));
		for(int i=0;i<b1.length;i++){
      b1[i]=new JButton(Integer.toString(i+1),new ImageIcon("D:/WorkSpace/images.gif"));
		b1[i].addActionListener(this);
		p1.add(b1[i]);
		p1.setVisible(false);
		}
		
		p2=new JPanel();
		p2.setLayout(new FlowLayout(FlowLayout.RIGHT));
		score=new JLabel("Your Score:      ");
		time=new JLabel("Timer:            ");
		p2.add(score);
		p2.add(time);
		
		Container c1=getContentPane();
		c1.setLayout(new BorderLayout());
		c1.add(p1,BorderLayout.CENTER);
		c1.add(p2,BorderLayout.SOUTH);
		
		System.out.println("i="+i);
		
	}
				
	/**
	 * This method initializes this
	 * 
	 */
	
	public void actionPerformed(ActionEvent e){
		
		if(e.getSource().equals(exit)){
			System.exit(0);
		}
		
		if(e.getSource().equals(newgame)){
			try{
				newgame.setEnabled(false);
				p1.setVisible(true);
				z*=0;
		    	score.setText("Your Score: "+z);
		    	System.out.println("z:"+z);
			}catch(Exception ex){
			System.err.println("Exception occurred :" + ex.toString());
				ex.printStackTrace();
			}
			
			Thread t=new Thread(){
				 public void run(){
					 
				for(a=1; a<=30; a++)
				{
					time.setText("Timer: "+ count);
					count++;
					if(a==30){
						count=1;
						newgame.setEnabled(true);
						p1.setVisible(false);
					
					}
				      
					try{
						repaint();
						Thread.sleep(500);
				}
					 catch(InterruptedException e)
					 {}
				}
				 }				
				} ;
				t.start();	
		}
		try{	
		String text=((JButton)e.getSource()).getText();
		System.out.println("Value of text " + text);
		i=Integer.parseInt(text);
		System.out.println("value of i:"+i);
	   		i--;
	    if(i==0)
	    {
	    System.out.println("Value 1: "+i);
	    b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/ad.gif"));
	    count1++;
	    System.out.println("count1:"+count1);
	    }
	    	    
	    if(i==1) {
	    	System.out.println("Value 2:"+i);
	    	
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/kd.gif"));
	    	count2++;	    	
	    	System.out.println("count2:"+count2);
	    }
	    	    
	    if(i==2){
	    	System.out.println("Value 3:"+i);
	    	
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/qd.gif"));
	        count3++;
	        System.out.println("count3:"+count3);
	    }
	    
	    
	    if(i==3)
	    {
	    	System.out.println("Value 4:"+i);
	    	
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/jd.gif"));
	        count4++;
	        System.out.println("count1:"+count1);
	    }
	    if(i==4)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/2d.gif"));
	    	count5++;
	    }
	    if(i==5)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/3d.gif"));
	    	count6++;
	    }
	    if(i==6)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/4d.gif"));
	    	count7++;
	    }
	    if(i==7)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/5d.gif"));
	        count8++;
	    }
	    if(i==8)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/6d.gif"));
	        count9++;    
	    }
	    if(i==9)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/7d.gif"));
            count10++;	    
	    }
	    if(i==10)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/8d.gif"));
	    	count11++;
	    }
	    if(i==11)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/9d.gif"));
	    	count12++;
	    }
	    if(i==12)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/td.gif"));
	    	count13++;
	    }
	    if(i==13)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/ah.gif"));
	    	count1++;
	    }
	    if(i==14)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/kh.gif"));
	    	count2++;
	    }
	    if(i==15)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/qh.gif"));
	    	count3++;
	    }
	    if(i==16)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/jh.gif"));
	    	count4++;
	    }
	    if(i==17)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/2h.gif"));
	    	count5++;
	    }
	    if(i==18)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/3h.gif"));
	    	count6++;
	    }
	    if(i==19)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/4h.gif"));
	    	count7++;
	    }
	    if(i==20)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/5h.gif"));
	    	count8++;
	    }
	    if(i==21)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/6h.gif"));
	    	count9++;
	    }
	    if(i==22)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/7h.gif"));
	    	count10++;
	    }
	    if(i==23)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/8h.gif"));
	    	count11++;
	    }
	    if(i==24)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/9h.gif"));
	    	count12++;
	    }
	    if(i==25)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/th.gif"));
	    	count13++;
	    }
	    if(i==26)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/as.gif"));
	    	count1++;
	    }
	    if(i==27)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/ks.gif"));
	    	count2++;
	    }
	    if(i==28)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/qs.gif"));
	    	count3++;
	    }
	    if(i==29)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/js.gif"));
	    	count4++;
	    }
	    if(i==30)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/2s.gif"));
	    	count5++;
	    }
	    if(i==31)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/3s.gif"));
	    	count6++;
	    }
	    if(i==32)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/4s.gif"));
	    	count7++;
	    }
	    if(i==33)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/5s.gif"));
	    	count8++;
	    }
	    if(i==34)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/6s.gif"));
	    	count9++;
	    }
	    if(i==35)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/7s.gif"));
	    	count10++;
	    }
	    if(i==36)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/8s.gif"));
	    	count11++;
	    }
	    if(i==37)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/9s.gif"));
	    	count12++;
	    }
	    if(i==38)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/ts.gif"));
	    	count13++;
	    }
	    if(i==39)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/ac.gif"));
	    	count1++;
	    }
	    if(i==40)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/kc.gif"));
	    	count2++;
	    }
	    if(i==41)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/qc.gif"));
	    	count3++;
	    }
	    if(i==42)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/jc.gif"));
	    	count4++;
	    }
	    if(i==43)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/2c.gif"));
	    	count5++;
	    }
	    if(i==44)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/3c.gif"));
	    	count6++;
	    }
	    if(i==45)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/4c.gif"));
	    	count7++;
	    }
	    if(i==46)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/5c.gif"));
	    	count8++;
	    }
	    if(i==47)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/6c.gif"));
	    	count9++;
	    }
	    if(i==48)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/7c.gif"));
	    	count10++;
	    }
	    if(i==49)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/8c.gif"));
	    	count11++;
	    }
	    if(i==50)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/9c.gif"));
	    	count12++;
	    }
	    if(i==51)
	    {
	    	b1[i].setIcon(new ImageIcon("D:/WorkSpace/cards/tc.gif"));
	    	count13++;
	    }
	    	    
	    if(count1==4){
	    	
	    	z+=10;
	    	score.setText("Your Score: "+z);
	    	System.out.println("count1="+z);
	    	count1-=4;
	    }
	    
	   if(count2==4){
	    	
	    	z+=10;
	    	score.setText("Your Score: "+z);
	    	System.out.println("count2="+z);
	    	count2-=4;
	    }
       if(count3==4){
	    	
    	   z+=10;
	    	score.setText("Your Score: "+z);
	    	System.out.println("count3="+count3);
	        count3-=4;    
       }
        if(count4==4){
	       
        	z+=10;
	       score.setText("Your Score: "+z);
	       count4-=4;
       }
        if(count5==4){
        	
        	z+=10;
	        score.setText("Your Score: "+z);
            count5-=4;	
       }
        if(count6==4){
        	
        	z+=10;
	        score.setText("Your Score: "+z);
	        count6-=4;
       }
         if(count7==4){
        	
        	 z+=10;
	         score.setText("Your Score: "+z);
	         count7-=4;
       }
          if(count8==4){
        	  
        	  z+=10;
	          score.setText("Your Score: "+z);
	          count8-=4;
       }
           if(count9==4){
        	  
        	   z+=10;
	           score.setText("Your Score: "+z);
	           count9-=4;
       }
            if(count10==4){
            	
            	z+=10;
	            score.setText("Your Score: "+z);
	            count10-=4;
       }
             if(count11==4){
            	
            	 z+=10;
	             score.setText("Your Score: "+z);
	             count11-=4;
       }
             if(count12==4){
            	 
            	 z+=10;
	             score.setText("Your Score: "+z);
	             count12-=4;
       }
              if(count13==4){
	          
            	  z+=10;
	          score.setText("Your Score: "+z);
	          count13-=4;
       }
	    
	    }
	catch(Exception ex){
		System.err.println("Exception occurred :" + ex.toString());
		ex.printStackTrace();
	}
	}
	//}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		cardgame c=new cardgame();
		
		c.setTitle("Card Game");
		c.setSize(800, 700);
		c.setVisible(true);
		
	}

}  //  @jve:decl-index=0:visual-constraint="10,10"

Stack Trace

Exception occurred :java.lang.ClassCastException: javax.swing.JMenuItem cannot be cast to javax.swing.JButton
java.lang.ClassCastException: javax.swing.JMenuItem cannot be cast to javax.swing.JButton
at cardgame.actionPerformed(cardgame.java:118)
at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
at javax.swing.AbstractButton.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Hi,


This is because the value of "i" is "0" (zero) and not the length of jButton.

ClassCastException: javax.swing.JMenuItem cannot be cast to javax.swing.JButton

What objects are using that action listener?
Are some of them JMenuItems?
Why do you assume that the object with action event is a JButton?

You could make separate action listeners for the JButtons and for the JMenuItems.

Comments on your code. Any time you have dozens of statements like this, one after the other, think about how to use an array:

b1.setIcon(new ImageIcon("D:/WorkSpace/cards/kd.gif"));

You could use the value of i as an index into an array of filenames:

String[] gifFNs = {..., "kd.gif", ...};
...
b1.setIcon(new ImageIcon(Path + gifFNs);

Edited 6 Years Ago by NormR1: n/a

This article has been dead for over six months. Start a new discussion instead.