动态地在JTabbedPane的不同选项卡中向多个JTextAreas添加文本?

时间:2015-05-11 18:12:52

标签: java dynamic jtable jtextarea jtabbedpane

因此,我点击了JTextArea单元格,动态地将JTabbedPane添加到JTable。我想知道如何动态设置JTextArea的文本。我正在尝试使用嵌套在getSelectedIndex()中的getComponentAt(),但这会返回Component而不是JTextArea,因此我将无法setText()办法。我想知道是否需要构建ArrayArrayList new JTextArea s并在每次选择一个单元格时添加到ArrayArrayList然后从getSelectedIndex()开始设置相应的JTextArea文本。必要的代码如下:

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);
        }
    }
});

2 个答案:

答案 0 :(得分:2)

您正在添加:

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

作为新标签。

这意味着,getComponentAt()将返回完全您添加的JPanel
JPanel类型为Component,其中包含JTextArea.

您可以做什么(因为此JPanel 包含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

作为助手方法:

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;
}

答案 1 :(得分:1)

您可以使用带有标签索引的Map,并在该索引处使用JTextArea进行评估:

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);

例如,当您想要获取当前所选标签索引的JTextArea时,只需查看Map

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