• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

using getComponentCount() (sorry long post)

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am developing a swing application and I need to be able to clear or reset all textfields radiobuttons ect.. to empty strings or their default value.
So I am writting a method that will use getComponentCount to find out how many components are on the form and then loop through them and reset them.
like this
import java.awt.event.*;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.*;
import java.awt.Component;
public class ClearActionListener implements ActionListener {
private JPanel p;
private Component comp;
private JPanel panel = new customerInfo_panel();
private JTextField text;
private JTextArea area;
private JCheckBox chkbox;
/** Creates new ClearActionListener */
public ClearActionListener(JPanel p) {
}

public void actionPerformed(ActionEvent evt){
String command = evt.getActionCommand();
int iCount;
iCount = 0;
if (command == "clear")
iCount = panel.countComponents();
/* while( iCount <= panel.countComponents())
{
if(comp.equals(text))
text.setText(" ");
else if(comp.equals(area))
area.setText(" ");
else if(comp.equals(chkbox))
chkbox.setSelected(false);
}*/

System.out.println("the name of the JPanel is " + panel);
System.out.println("the count of the components on the panel is "+ iCount);
System.out.println("In the actionPerformed method in the ClearActionListener class");
}
}
the problem being that iCount always returns 0.
therefore my question is how does one get this method to work.
sorry this is such a long post
 
Michael Hildner
Ranch Hand
Posts: 297
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is just an idea, but are you sure that command == "clear" is true? Usually you don't want to use the == to compare Strings, since it only checks to see if the Strings are stored in the same place in memory. Try using if (command.equals("clear")){...}
While I was looking through the API, I noticed that the countComponents() method is deprecated. It has been replaced by getComponentCount().
Hope this helps.
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are quite correct, Michael. (command == "clear) is going to always return false.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic