How can I avoid JTextArea from grabbing focus upon setting text
Hello,
I have a view which contains a JTextArea and a JTree, and my JTextArea is updated to display information for the selected node in the tree upon every new selection.
The problem i experience is that when the JTextArea is not visual to the user (e.g. when scroll bars are used) then the setText function cause to focus on the JTextArea, loosing the focus/view of the node in the tree.
How can I use the setText option along with the option to ignore grabbing focus?
Thanks!
Re: How can I avoid JTextArea from grabbing focus upon setting text
After calling setText, try calling requestFocus on your JTree.
Re: How can I avoid JTextArea from grabbing focus upon setting text
Thanks, but I am afraid that does not help :-(
The problem is when the node and the jtextarea can not be displayed together on the view (i.e. when scroll bars are displayed since due to large amount of nodes in the tree, and the nodes and the jtextarea are located on opposite locations of the view therefore are not seen simultanousely on the screen) -
If I can not force the jtextarea to avoid the request focus after setting the text - How can I return to the same selected node on the tree?
I tried using:
myTree.setSelectionPath(theSelectedPath);
myTree.scrollPathToVisible(theSelectedPath);
but it did not work.
Thanks!
Re: How can I avoid JTextArea from grabbing focus upon setting text
To get better help sooner, post a SSCCE.
SSCCE : Java Glossary
db
Re: How can I avoid JTextArea from grabbing focus upon setting text
This is partial of my code:
JPanel myPanel = new JPanel();
myPanel.setLayout( new GridBagLayout() );
GridBagConstraints gbc= new GridBagConstraints();
JTree myTree = new JTree();
myTree.addMouseListener(this);
myTree.getSelectionModel().setSelectionMode(TreeSe lectionModel.SINGLE_TREE_SELECTION);
EMyObject basicRoot = new EMyObject();
TreeModel treeModel = new DefaultTreeModel(new DefaultMutableTreeNode(basicRoot));
myTree.setModel(treeModel);
myTree.setCellRenderer(getTreeCellRenderer());
myTree.addTreeSelectionListener(this);
JScrollPane treeScrollPanel = new JScrollPane(myTree);
myPanel.add(treeScrollPanel, gbc);
gbc.gridy++;
JTextArea myTextArea = new JTextArea();
myPanel.add(myTextArea, gbc);
Via this function I catch the change of the selection in the tree and update the JTextArea with the updated message, and then try to return the focus and slection to the selected node. The problem is that when scroll are displayed the selection and focus are done but the scroll do not move to display that node.
public void valueChanged(TreeSelectionEvent e)
{
if (e.getSource() instanceof JTree)
{
String myText = "";
if (e.getNewLeadSelectionPath() != null &&
e.getNewLeadSelectionPath().getLastPathComponent() != null)
{
myText = e.getNewLeadSelectionPath().getLastPathComponent() .toString();
}
myTextArea.setText(myText);
myTree.scrollPathToVisible(e.getNewLeadSelectionPa th());
}
}
Thanks a lot!