Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

dissapearing controls 2

Status
Not open for further replies.

Alira

Programmer
Mar 21, 2001
77
CA
Hi all!

So, I've created my forst applet and even captured button actions:)
But as soon as I click on the button all other controls dissapearing!
Why is this happening and how to solve this problem? Have a great day!:)
 
I can not even guess with out seeing your code. Any number of things could be happing. If you post the Applet code I will see if I can help you.

Rodney
 
Here is the code. Please note the remarks... I have a few more questions in there if you don't mind:))
Oh.. it's perfectly aligned, but I'll work on it:))
Thank you in advance:)


import java.awt.event.*;
import java.applet.*;
import java.io.*;
import java.lang.*;
import javax.swing.*;
import java.awt.*;


public class New extends JApplet
{
//declaring variables
JTextField txtUserName;
JTextField txtLastName;
JTextField txtFirstName;
JTextField txtEmail;
JComboBox chLevel;
JButton btnRegister = new JButton("Register");
JButton btnClear = new JButton("Clear");
RegisterListener alr=new RegisterListener();
ClearListener alc=new ClearListener();

JLabel Label1 = new JLabel();
JLabel Label2 = new JLabel();
JLabel Label3 = new JLabel();
JLabel Label4 = new JLabel();
JLabel Label5 = new JLabel();
JLabel Label6 = new JLabel();
JLabel Label7 = new JLabel();
JLabel Label8 = new JLabel();
JLabel Label9 = new JLabel();


javax.swing.JPasswordField JPasswordField1 = new javax.swing.JPasswordField(12);
javax.swing.JPasswordField JPasswordField2 = new javax.swing.JPasswordField(12);

public void init()
{
setContentPane(makeContentPane());
}

public Container makeContentPane()
{
btnRegister.addActionListener(alr);
btnClear.addActionListener(alc);

Container cp = getContentPane();

resize(310,350);
Label1.setText("User Name");
cp.add(Label1);
Label1.setBounds(65,12,60,20);
txtUserName=new JTextField(13);
cp.add(txtUserName);
txtUserName.setBounds(140,12,85,18);

Label2.setText("Password");
cp.add(Label2);
Label2.setBounds(70,45,50,20);
cp.add(JPasswordField1);
JPasswordField1.setBounds(140,45,85,18);

Label3.setText("Re-enter Password");
cp.add(Label3);
Label3.setBounds(15,78,115,20);
cp.add(JPasswordField2);
JPasswordField2.setBounds(140,78,85,18);

Label4.setText("Last Name");
cp.add(Label4);
Label4.setBounds(65,111,55,20);
txtLastName=new JTextField(20);
cp.add(txtLastName);
txtLastName.setBounds(140,111,120,18);

Label5.setText("First Name");
cp.add(Label5);
Label5.setBounds(65,144,55,20);
txtFirstName=new JTextField(20);
cp.add(txtFirstName);
txtFirstName.setBounds(140,144,120,18);

Label6.setText("E-mail");
cp.add(Label6);
Label6.setBounds(75,177,55,20);
txtEmail=new JTextField(35);
cp.add(txtEmail);
txtEmail.setBounds(140,177,135,18);

//combobox
Label7.setText("Your level is");
cp.add(Label7);
Label7.setBounds(75,211,55,20);
String[] myArr= {"Beginer","Intermediate","Advanced"};
chLevel=new JComboBox(myArr);
cp.add(chLevel);
chLevel.setBounds(155,211,60,20);

//buttons
cp.add(btnRegister);
btnRegister.setBounds(140,244,85,23);
cp.add(btnClear);
btnClear.setBounds(235,244,85,23);

return cp;
}

class RegisterListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String name =((JButton)e.getSource()).getText();
if(name=="Register")
{
//I was just making sure it works
Label1.setText(name);

}
}
}

class ClearListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String name =((JButton)e.getSource()).getText();
if(name=="Clear")
{
String st="";
setUserName(st);
}
}
}

public String getUserName()
{
return txtUserName.getText();
}

public void setUserName(String s)
{
txtUserName.setText(s);
}

public String getFirstName()
{
return txtFirstName.getText();
}

public String getLastName()
{
return txtLastName.getText();
}

public String getEmail()
{
return txtEmail.getText();
}

//Here I can't figure out how to return selected item
//from combobox.......... How to convert Object(getSelectedItem)
//to string??
public String getLevel()
{
String st;
st=chLevel.getSelectedItem();
return st;
}


}
Have a great day!:)
 
Well the problem is you are trying to layout out your componets as if you are grid with no layout manager. When the default layout manager for a Applet is FlowLayout. So your last component you add ends up taking up the whole container but in the back ground. So if you click on the background or a label the clear button is brought to focus.

To make a long story short, if you want to layout your components like you are you need to set the layout manager to null. To do this you would add this to your code:
Code:
cp.setLayout(null);
Right after you get the content pane of the applet.

Then everything works the way I think you expect it to.

However if you want a little bit of advice I would recommend that you never use a null layout. You should always use a LayoutManager. Depending on what you are try to layout and visualize depends on which you should use. I recommend that you get a good book that goes over the layout managers in detail so you can learn how to use each one. My personal favorite is GridBagLayout, and I use it for almost all my main display areas.

I would recommend a GridbagLayout for your main display area, and a FlowLayout for the button panel at the top.

There is so many ways you can do it. You just need to get in there and play with the layout managers.

As for the other question in your codes comments (I only say one). You asked how do you convert an Object to a String. Well if that Object is really a String then you just need to cast it to a String like so:
Code:
st = (String)chLevel.getSelectedItem();
However if you are wrong about the cast a ClassCastException will be thrown. In your case you know for sure that you are going to get a String since you put a String in. However in other cases when you case and you are not sure what you are getting, you test the Object you want to cast first. You do this by using the keyword "instanceof" example:
Code:
Object obj = new String("Object");
String str = null;

if (obj instanceof String)
    str = (String)obj;
[code]
You could also just catch the exception and handle it that way.  I personally do not like that for it make the code harder to read, and just is not as clean.

Anyways I hope this helps you... have fun...

Rodney
[URL unfurl="true"]http://www.javathis.com[/URL]
 
Thanks a lot Rodney!:)
I hope you'll help me in the future, 'cause I have plenty of questions:) Have a great day!:)
 
I will do my best to help you when I can. As long as you do not always expect a fast reply hehe :)

You can contact me via my website if you have future questions. I have two active open source projects, and forums specificly for them. Feel free to check them out if you are interested.

Looking over other peoples code, and trying to figure it out is a great teacher in itself.

I wasn't going to ask before, but looking at your code, made me think that you might be a VB programmer? Would that be the case ? hehe :) If so how do you like Java so far?

Good luck...

Rodney
 
BTW Alira if you really find any of the posts helpful, it would be nice if you click the link associated with the helpful response. They say something like this:

Click here to mark this
post as a helpful
or expert post!

Thanks :)

Rodney
 
well, im not Alira, but I did find some of your comments helpful. You definitely deserve two starts ;)
Avendeval


 
Rodney!!:))
I did marked your reply as helpful!:)Haven't you noticed?:)
And you're right, I am a VB programmer:)))

I like Java, but VB makes it difficult... Now, I'm trying to validate input on this form and get confused..
Can't find any good exapmles ...

Any suggestions?:)) Have a great day!:)
 
I am going to assume you want to validate the input prior to the user registering.

For a simple form like this the best way I can suggest is to add the validation code insade your RegisterListener. To do this you are going to need to get ride of this class. My recommendation is to make it an anonyomous listener for the register button, are at least have the applet implement ActionListener so you can set the applet as it listener. Example of the anonyomous way using your above code:
Code:
btnRegister.addActionListener(new ActionListener()
{
  public void actionPerformed(ActionEvent e)
  {
    // Add validation code here...
    
    // If everything is good then 
    // preform your registration code...
    
    // If something is invalid you may 
    // you may want to prompt a option
    // informing the user of ALL the errors
    // then when the user OK's this 
    // message then take them to the field
    // of the first error, and select all
    // the text for them.
  }        
});
When you do this it this way you know for a FACT that when this actionPerformed method is called that it is from your register button. The drwaback to this way is you can not remove the listener form the component. If it is required that you need to add and remove it at various times to the running of a application then you would want to have your Applet in this case implement the interface. With action listernes this is rarely the case though. :)

So now you have access to all your componets in your applet, and you can get the text from the fields and make sure it is with in the bounds of your requirements.

By the validation at the end when the user is telling the program it is finished (clicking on a OK button, or in your case the Register button) the user can make changes as they feel, and enter the data in the order they feel like. Some programmers have added the validation to EACH component so that the user can not leave the field until the info is valid. This is only useful is rare cases, and makes it difficult for the user of the program.

Anyway... I hope that helps...

Rodney

PS...
My JTUtilities project has a JTTextField and a JTLabel ui components which may work well for your program. You may want to give them a look. :)
 
You see how fast I'm learning?:))You've got another star!:))

I understand everything except one thing...
I will verify input and it's not a big deal, but if there is an error action has to be canceled. And I'm not sure I know how to do that... Have a great day!:)
 
Alira,

Not actully, because no "action" should have be taken yet.

Let say for simplicity at the start of the actionPreformed method you create a boolean value called 'isValid' and set it equal to true. Then as you validate each field you only set isValid to false if validation failed. Then after validation is done, and before you commit the registration. You would just pop up a JOptionPane and say that a field is invalid and then after they click OK on this, you just return from the method.

This is not the best coding style discribed above but I hope it shows you what you need to do. See psuedo code below, it shows a more robust method (code block will not compile):
Code:
public class MyApplet extends JApplet
{
  actionPreformed()
  {  
    boolean isValid = true;
    ArrayList invalidFields = new ArrayList();
  
    if (fieldOne is not valid)
    {
      isValid = false;
      invalidFields.add(fieldOne.getName());
    }
  
    if (fieldTwo is not valid)
    {
      isValid = false;
      invalidFields.add(fieldTwo .getName());
    }
  
    ..etc..
  
    if (!isValid)
    {
      Iterator iter = invalidFields.iterator();
      String[] message = new String[invalidFields.size() + 1];
      
      message[0] = "The following components have failed validation:";
      
      for (int i = 1; i < message.length; i++
          message[i] = (String)iter.next();  
          
      JOptionPane.showMessageDialog(MyApplet.this, message, &quot;
                  Validation Failed&quot;, JOptionPane.ERROR_MESSAGE)
    }
    else
    {
      ...Everything is okay, so complete registration...
    }
  
  }
}

As you can see this is along the same lines as my previous description, however it is a little better coded, and easier to read, and understand. (I hope).

Does this help?

Rodney
 
Rodney, your explanations are very clear!
Thanks a lot!:)

Have a great day!:)
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top