Using JTextarea with JTabbedPanel

2019-09-05 06:20发布

问题:

JTextarea is dynamically created and added to the jTabbed panel using the code:

            // tabidis is a variable with unique value in each case

            JScrollPane panel2 = new JScrollPane();
            panel2.setName(tabidis);

            ta = new JTextArea("");
            ta.setColumns(30);
            ta.setRows(20);
            ta.setEditable(false);
            panel2.setViewportView(ta);
            ta.setName(tabidis);

            jTabbedPane1.add(username4, panel2);

When new tabs are added (ta textarea is added along with it), the last tabs textarea recieves all the text.

 private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt){
                send3 = ta.getName();
                ta.setName(send3);
                ta.setText(ta.getText()+send3);
                }

In the above code you can see that The text in both the textareas(In two tabs) should be updated. But what really happens is that only the second TextArea is getting updated.The first TextArea is not updated.

回答1:

ta only have a value at a time, what you need is a Collection of TextArea you have to have a reference to them for example in a List<JTextArea> textAreas

Then in your code

        JTextArea ta = new JTextArea("");
        ta.setColumns(30);
        ta.setRows(20);
        ta.setEditable(false);
        textAreas.add(ta);

And in your event something like this:

private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt){
                for(JTextArea ta : textAreas ){
                 send3 = ta.getName(); // this line an below are redundant
                 ta.setName(send3);
                 ta.setText(ta.getText()+send3);
               }
}