GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes Help Me Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Help Me" Watch "Help Me" New topic
Author

Help Me

Van Jordan
Greenhorn

Joined: May 18, 2006
Posts: 4
The following code is taken from an exersize in Java Programming by Shelly/Cashman. It compiles fine, but doesnt work. I think it has something to do with the layout. Thanks in advance.


import java.awt.*;
import java.awt.event.*;


public class Checkerboard extends Frame implements ActionListener
{
TextField textFieldArray[] = new TextField[15];
Panel arrayPanel = new Panel();
TextField textField1 = new TextField();
TextField textField2 = new TextField();
TextField textField3 = new TextField();
int start, stop, step;
Label startLabel = new Label("Start");
Label stopLabel = new Label("Stop");
Label stepLabel = new Label("Step");
Button go = new Button("Go");
Panel fieldPanel = new Panel();

public Checkerboard()
{
int start=0, stop=0, step=0;
this.setLayout(new BorderLayout());
arrayPanel.setLayout(new GridLayout(4,4));
fieldPanel.setLayout(new GridLayout(2,3));



fieldPanel.add(textField1);
fieldPanel.add(textField2);
fieldPanel.add(textField3);
fieldPanel.add(startLabel);
fieldPanel.add(stopLabel);
fieldPanel.add(stepLabel);
fieldPanel.add(go);

add(arrayPanel, BorderLayout.NORTH);
add(fieldPanel, BorderLayout.SOUTH);

go.addActionListener(this);

add(arrayPanel);
add(arrayPanel);

for(int i =0; i<15; ++i)
{
;
arrayPanel.add(textFieldArray[i]);
textFieldArray[i].setEditable(false);
textFieldArray[i].setText(Integer.toString(i));
}

;

} //end constructor

public void actionPerformed(ActionEvent e)
{
start = Integer.parseInt(textField1.getText());
stop = Integer.parseInt(textField2.getText());
step = Integer.parseInt(textField3.getText());

for(int i =0; i<15; ++i)
{
textFieldArray[i].setBackground(Color.MAGENTA);
}
for(int i=start; i<stop; ++step)
{
textFieldArray[i].setBackground(Color.YELLOW);
}
}

public static void main(String[] args)
{
Checkerboard f = new Checkerboard();
f.setBounds(50,100,300,400);
f.setTitle("Checkerboard Array");
f.setVisible(true);
}
}
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
a reasonably common error

this line allocates the space, but does not create the objects
TextField textFieldArray[] = new TextField[15];

when creating objects you (generally) need 2 things
new
()
where () can be empty or can contain arguments

in this case add the indicated line
for(int i =0; i<15; ++i)
{
textFieldArray[i] = new TextField(5);//<-----------------included 5, for size
arrayPanel.add(textFieldArray[i]);
 
GeeCON Prague 2014
 
subject: Help Me