开发者

Is it not possible to add text to a single JTextArea dynamically?

开发者 https://www.devze.com 2023-03-04 20:54 出处:网络
i am developing a GUI using Java Swing. but i got stuck here. Is it not possible to add text to the single \"JTextArea\" dynamically?

i am developing a GUI using Java Swing. but i got stuck here. Is it not possible to add text to the single "JTextArea" dynamically?

Ex:

class Sample extends JFrame{

    public static void fn(int n) {
        JFrame f = new JFrame();
        JTextArea ta = new JTextArea();
        f.add(ta);
        f.setVisible(true);
        for(int i=1;i<=n;i++){
           //some processing is done
         ta.setText(" step is done");
           // some other stuffs  
        }  
    }
}

this is just part of my source code. My problem here is , in this code for each iteration of the "for loop" i am getting a new frame with the text " step is done". but inst开发者_JS百科ead i want it to be displayed on a single frame 'n; times.


I would change your code to:

class Sample { // no need to extend JFrame here

    public static void fn(int n) {
        JFrame f = new JFrame();
        JTextArea ta = new JTextArea();
        f.add(ta);
        f.setVisible(true);
        for(int i = 0; i < n; i++) {

           // ... *** don't create a new JFrame here ***

           ta.append(" step is done\n");

           // ... *** and don't create a new JFrame here ***

        }  
    }
}

We'll be able to give you more details if/when you show us what you're doing in the commented out bits in your original post's code.


import javax.swing.*;

// don't extend JFrame unless adding functionality
//class Sample extends JFrame{
class Sample {

    JTextArea ta;

    Sample() {
        JFrame f = new JFrame();
        ta = new JTextArea(10,35);
        // to look better
        ta.setLineWrap(true);
        ta.setWrapStyleWord(true);
        //should be in a JScrollPane
        f.add(ta);
        // important
        f.pack();
        f.setVisible(true);
    }

    public void fn(int n) {
        for(int i=1;i<=n;i++){
           //some processing is done
         ta.append(" step is done");
           // some other stuffs
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Sample sample = new Sample();
                sample.fn(40);
            }
        });
    }
}


setText() method sets the text, not appends its. You'll have to do that manually:

ta.setText(ta.getText() + "\nStep is done.");

EDIT:

My bad, I didn't use Swing for a while and simply forgot about such a basic thing as append(). You should accept @Hovercraft Full Of Eels answer as it's a correct and much better one.

0

精彩评论

暂无评论...
验证码 换一张
取 消