Hot questions for Using Applets in textfield

Question:

I have this applet (above is the image) with 2 text field. How do I separate these text fields to different lines?

code

import java.applet.*;
import java.awt.*;

public class Print extends Applet {
    TextField text1,text2;
    public void init(){ 
        text1=new TextField(8);
        text2=new TextField(8);  
        add(text1);
        add(text2);

    }
   public void paint(Graphics g) { 
      g.drawString("Welcome in Java Applet.",40,200);
   }
}

Answer:

The simplest method is using setBounds(x,y,width,height). In your case use code as below

text1.setBounds(10,100,100,20);
text2.setBounds(10,130,100,20);

Question:

Basically I have created an applet that has three textfields one for each of the RGB values. I then created a try catch block to show a dialogue message if the user inputs a string. However, now I want it to find which textfield it was that had a string in it and set only that textfield to null so then they can type an integer, whilst also keeping the values of the two correct textfields.

So for example:

[255] [150] [cat]   
step 2: [255] [150] []  (the string textfield should become null)

Code:

try{
        if (e.getSource().equals (bttn))
        {

            as=T1.getText();
            ag=T2.getText();
            ab=T3.getText();
            as=as.trim();
            ag=ag.trim();
            ab=ab.trim();

            redColor= Integer.parseInt(as);
            greenColor= Integer.parseInt(ag);
            blueColor= Integer.parseInt(ab);
        }
    }
    catch (NumberFormatException exception){
        JOptionPane.showMessageDialog(null,"Integers Only","ERROR!",JOptionPane.WARNING_MESSAGE);

    }

Answer:

You have to split your code into tree parts, one for each field.

But this would result in redundant code. To avoid this, you should put the conversion part into a separate function which is called for each field.

Question:

I have a Java Applet for login form. It has 2 TextFields, username and password. I need to clear them on clicking Reset button. This is the code I have written.

  public class LoginForm extends Applet implements ActionListener
  {
    TextField name, pass, hidden;
    Button b1, b2;

    public void init()
    {
        name = new TextField(20);
        pass = new TextField(20);

        b2 = new Button("Reset");

        add(name);
        add(pass);
        add(b2);

        b2.addActionListener(this);
    }

    public void paint(Graphics g)
    {
        g.drawString("Hello", 10, 150);
    }

    public void actionPerformed(ActionEvent e) {
        System.out.println(e);

        name.setText("");
        pass.setText("");

        repaint();
    }
  }

But this is not working properly.

Once I click the Reset button, the actionPerformed() method gets called and it also calls repaint(). (I can see "Hello" being displayed).

But the TextFields do not get cleared.


If I make following changes in actionPerformed

        name.setText(" ");  // please note the spaces
        pass.setText(" ");

then it works. But I don't want spaces there. I want the TextFields to get blank.

Any help is appreciated.


Answer:

Probably it is not good solution, but this is a workaround.Before setting the text invoke getText method and it will reset. Pretty strange! This behaviour is marked as Bug on this page

public void actionPerformed(ActionEvent e) {
    System.out.println(e);
    name.getText();
    pass.getText();

    name.setText("");
    pass.setText("");

    repaint();
    revalidate();
}

Another solution would be setting text with space. But not if you have password-like fields which have setEchoChar('*').

public void actionPerformed(ActionEvent e) {
    System.out.println(e);

    name.setText(" ");
    pass.setText(" ");

    repaint();
    revalidate();
}

Question:

public Monster createCharacterScene() {
    String name;
    TextField nameTextField = new TextField();
    nameTextField.setLocation(65, 50);
    nameTextField.setSize(60, 10);
    Button myButton = new Button("OK");
    myButton.setLocation(25, 50);
    myButton.setSize(30, 40);
    add(myButton);
    add(nameTextField);
    myButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            name = nameTextField.getText();
        }
    });
    return null;
}

I can't do it like this. They says "local variables referenced from an inner class must be final or effectively final". Is there alternative way to do it?

Thanks a lot.

PS. I using applet.


Answer:

You cannot read this value directly in createCharacterScene() method. Because it's unknown yet. The only thing you can do is to define a eventHandler, that will be triggered, on key press.

Consumer<String> nameConsumer = text -> { /*You will handle event here*/};
myButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            nameConsumer.apply(nameTextField.getText());
        }
    });

The cheaper version would be to use a small workaround for final modifier:

final String[] nameHolder = new String[1];
myButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            nameHolder[0] = nameTextField.getText();
        }
    });

Here nameHolder will initially hold null, but when someone will trigger the event, it's value will be set, so you need to check if value is set or not.

Question:

In my applet program I have the TextField declared in my public class header as:

TextField numbers [][] = new TextField[5][5];

I also have a button that is supposed to clear all the textboxes when clicked.

Right now I basically have this:

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        numbers.setText("");
    }
});

But I'm getting an error: "Cannot invoke setText(null) on the array type TextField[][]"

How can I fix this?


Answer:

Key lesson here: read the error message critically as it is telling you exactly what is wrong.

"Cannot invoke setText(null) on the array type TextField[][]"

You're treating the numbers variable as if it's a single TextField and it's not, and so you can't call setText(...) on it -- rather it's a 2D array of objects. A solution is to think of how you interact with any similar 2-d array, how do you call methods on each item held within the array: use nested for loops to iterate through the array.

for (int i = 0; i < numbers.length; i++) {
    for (int j = 0; j < numbers[i].length; j++) {
       numbers[i][j].setText("");
    }
}

Also, change TextField to JTextField so that you're using all Swing components:

// change type from TextField to JTextField
JTextField numbers [][] = new JTextField[5][5];