简体   繁体   中英

Adding text to multiple JTextAreas in different tabs of a JTabbedPane dynamically?

So I am dynamically adding JTextArea s to a JTabbedPane on the click of a JTable cell. I was wondering how to also set the text of the JTextArea dynamically. I was looking at trying to use getSelectedIndex() nested in getComponentAt() , but this returns a Component rather than a JTextArea so I will not be able to setText() this way. I'm wondering if instead I need to build an Array or ArrayList of new JTextArea s and add to the Array or ArrayList each time a cell is selected and then from the getSelectedIndex() and set the corresponding JTextArea s text. The necessary code is below:

table.addMouseListener(new MouseAdapter() {
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() == 2) {
            int row = table.getSelectedRow();
            viewerPane.addTab((String) table.getValueAt(row, 0), null , new JPanel().add(new JTextArea()), (String) table.getValueAt(row, 0));
            viewerPane.setSelectedIndex(viewerPane.getComponentCount()-1);
        }
    }
});

You are adding:

 new JPanel().add(new JTextArea())

as new Tab.

That means, getComponentAt() will return exactly this JPanel you added.
This JPanel is type of Component and contains your JTextArea.

What you could do (since this JPanel does only contain a JTextArea ):

//verbose code:
Component cmp = tab.getComponentAt(0 /*index of tab*/);
JPanel pnl = (JPanel)cmp; //cast to JPanel
Component cmp2 = pnl.getComponent(0);  //get first child component
JTextArea textArea = (JTextArea)cmp2; //cast to JTextArea

as Helper-Method:

public JTextArea getTextAreaFromTab(JTabbedPane p_tabbedPane, int p_tabIdx)
{
   Component cmp = p_tabbedPane.getComponentAt(p_tabIdx /*index of tab*/);
   JPanel pnl = (JPanel)cmp; //cast to JPanel
   Component cmp2 = pnl.getComponent(0);  //get first child component
   JTextArea textArea = (JTextArea)cmp2; //cast to JTextArea
   return textArea;
}

You can use a Map keyed with the tab index and valued with the JTextArea at that index:

Map<Integer, JTextArea> indexToTextArea = new HashMap<>();//Instance variable
....
//in the MouseListener:
JTextArea textArea = new JTextArea();
viewerPane.addTab((String) table.getValueAt(row, 0), null , new JPanel().add(textArea), (String) table.getValueAt(row, 0));
viewerPane.setSelectedIndex(viewerPane.getComponentCount()-1);
indexToTextArea.put(viewerPane.getComponentCount()-1, textArea);

When you want to get the JTextArea of the currently selected tab index for instance, just look up in the Map

JTextArea selectedTextArea =  indexToTextArea.get(viewer.getSelectedIndex());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM