0

Hi i have following problem my applet should print characters to applet along to vertical line, but it prints only last character from a string. i try to move repaint() method in different places outside inside the loop but it still print out only last character in string. When i use //System.out.print(letters[i]); or //System.out.println(text); to check what is the content of string or charArray it prints right output but my paint g method prints only the last char form array Any suggestions??

public class ExtensionExercise extends Applet implements ActionListener {
    String text;
    String output;
    Label label;
    TextField input;
    int xCoordinates = 30, yCoordinates = 50;
    char letters [];
    public void init(){
        label = new Label("Enter word");
        add(label);
        input = new TextField(10);
        add(input);
        input.addActionListener(this);
    }
    public void start(){
        text = "";
    }
    @Override
    public void actionPerformed(ActionEvent event) {
        text = event.getActionCommand();
        letters = text.toCharArray();

        for(int i = 0; i<letters.length; i++){
            text = String.valueOf(letters[i]);
            xCoordinates +=10;
            yCoordinates +=10;
        }
        repaint();
    }
    @Override
    public void paint(Graphics g){      
        g.drawString(text, xCoordinates, yCoordinates);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 1) Why code an applet? If it is due to spec. by teacher, please refer them to [Why CS teachers should stop teaching Java applets](http://programmers.blogoverflow.com/2013/05/why-cs-teachers-should-stop-teaching-java-applets/). 2) Why AWT rather than Swing? See my answer on [Swing extras over AWT](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon using AWT components. – Andrew Thompson Mar 22 '14 at 03:39

1 Answers1

1

You're only calling repaint once after the for loop so obviously only the last letter will appear. All the letter selection logic needs to appear in the paint method itself

@Override
public void paint(Graphics g) {
    super.paint(g);

    for (int i = 0; letters != null && i < letters.length; i++) {
        text = String.valueOf(letters[i]);
        g.drawString(text, xCoordinates, yCoordinates);
        // xCoordinates += 10; remove this
        yCoordinates += 10;
    }
}

Note you don't want to increment the xCoordinates offset to achieve vertical output

Reimeus
  • 158,255
  • 15
  • 216
  • 276