Search code examples
javaswingjbuttonactionlistener

How to make the text generated by a JButton reappear at the same place if clicked on twice?


I have a JButton that displays random text when clicked on but my problem is that if I click on it twice it will display random text again but to the side of the first one when I'd like it to displays at the exact same place instead of the first one (hope I'm being clear in what i'm saying haha)

I've already tried googling the problem and searching on reddit and stackoverflow but couldn't find what I'm looking for

Code of the button :

butt = new JButton("Generate");
        butt.setFont(new Font("Tahoma", Font.BOLD, 12));
        butt.setBackground(Color.WHITE);
        butt.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent e) {
                RandomString yep = new RandomString();
                String c = yep.nextString();
                text = new JTextArea("                                                                          "+c,0,0);
                text.setLineWrap(true);
                text.setBounds(10,10,100,60);
                text.setFont(new Font("Courier", Font.BOLD, 14));

                text.setEditable(false);
                p3.add(text,BorderLayout.CENTER);
                f.remove(p4);
                f.add(p3,BorderLayout.CENTER);
            }
        });

If this was perfect it would display the text in a first click and in the second click it would display the text again but this time exactly where the first text was as if it was erasing it and displaying it again

I really hope this is understandable ! Thanks for any help that's like the final touches to this program :)


Solution

  • You are creating a JTextArea every time you perform action! Move the JTextArea out of the actionPerformed and set your text.

    JTextArea text = new JTextArea();
    JButton button = new JButton("Generate");
    ....
    button.addActionListener(new ActionListener() {
        ....
        String c = yep.nextString();
        text.setText(c);
        ....
    }