-2

I am trying to create a JPanel that asks whether the player wants to hit or stand in a Black Jack game.

public class decisionLayout extends JFrame
{
JPanel decisionPanel; 

public JButton buttons[];

private final String names[] = { "YES", "NO" };

final static String ASK_FOR_DECISION = "Decide whether to hit or not.";

public decisionLayout() 
{ 
    super( "decisionPanel demo" ); 

    JPanel panel = new JPanel();
    JPanel TextFieldPanel = new JPanel(); 
    final JTextField tf = new JTextField(); 
    tf.setText( ASK_FOR_DECISION ); 

    tf.setEditable( false );  
    TextFieldPanel.add( tf );

    // create the decisions 
    JPanel decisionPlace = new JPanel(); 

    for ( int count = 0; count < buttons.length; count++ )
    { 
        buttons[ count ] = new JButton( names[ count ] ); 
        buttons[ count ].addActionListener( 
            new ActionListener() 
            { 
                public void actionPerformed( ActionEvent e )
                { 
                    if( e.getSource() == buttons[ 0 ] )
                    { 
                        tf.setText( "Yes. You want more cards." );
                    }
                    else
                    { 
                        tf.setText( "No. You do not want more cards." );
                    }
                }
            }
        );
    }

    JPanel decisionPanel = new JPanel(); 
    decisionPanel.add( decisionPlace );

    panel.add( TextFieldPanel, BorderLayout.PAGE_START ); 
    panel.add( decisionPanel, BorderLayout.CENTER );
}

} `

I do not see why there is a compilation error at line:

 for ( int count = 0; count < buttons.length; count++ )

,which is what eclipse keeps telling me. Does anybody have any ideas why this is happening?

Web
  • 17
  • 4

2 Answers2

1
public JButton buttons[];

You never initialize your buttons, so when you try to call buttons.length you get an NPE. You probably want to actually place some buttons in that array

Dragondraikk
  • 1,659
  • 11
  • 21
1

You never initialize the buttons[]. buttons[] has no length:

for ( int count = 0; count < **buttons.length**; count++ )
brso05
  • 13,142
  • 2
  • 21
  • 40