Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

variable problem.....  RSS feed

 
mayank yadav
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi....in the given codes
after compiling iam getting an error
VARIABLE hos not found.....
please help me to correct it...

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

public class List extends JFrame
{
public String s;
JFrame f;
JPanel po;
JComboBox cb;
JTextField tf;


public static void main (String arg[])
{

List obj = new List();
}


public List()
{


f = new JFrame("list");
po= new JPanel();
tf= new JTextField(30);
f.getContentPane().add(po);
f.setVisible(true);
f.setSize(300,300);
String[] hos = {"Hostel1","Hostel2","Hostel3","hostel4","hostel6"};
cb = new JComboBox(hos);
cb.setMaximumRowCount(3);
//cb.addItemListener(this);
po.add(cb);
po.add(tf);
process();



}

public void process()
{
s= hos[cb.getSelectedIndex()];
tf.setText(s);

}
}
 
Layne Lund
Ranch Hand
Posts: 3061
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You have declared hos as a String[] in the constructor. This means that it has local scope and is not available in the process() method. I think the best way to fix this is to use the getSelectedItem() method rather than using the getSelectedIndex(). This is because getSelectedItem() will return the String object directly. This is also safer because the ComboBox may have been edited so that the indices do not correspond to the indices in the array that was used to create the ComboBox.

HTH

Layne
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!