JTree events seem wrong

It seems to me that tree selection events should happen after focus events, but that doesn't seem to be the case. Suppose you have JTree and JTextField, where the JTextField is populated with what is selected in the tree. When the user changes the text field, when the focus is lost, you update the tree from the text field. however, the tree selection changes before focus is lost in the text box. this is wrong, right? Any ideas? Here is a sample code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;

public class Focus extends JFrame
{
 public static void main(String[] args)
 {
  Focus f = new Focus();
  f.setLocationRelativeTo(null);
  f.setVisible(true);
 }

 public Focus()
 {
  Container cp = getContentPane();
  cp.setLayout(new BorderLayout());

  final JTextArea ta = new JTextArea(5, 10);
  cp.add(new JScrollPane(ta), BorderLayout.SOUTH);

  JSplitPane sp = new JSplitPane();
  cp.add(sp, BorderLayout.CENTER);

  JTree t = new JTree();
  t.addTreeSelectionListener(new TreeSelectionListener()
  {
   public void valueChanged(TreeSelectionEvent tse)
   {
    ta.append("Tree Selection changed\n");
   }
  });
  t.addFocusListener(new FocusListener()
  {
   public void focusGained(FocusEvent fe)
   {
    ta.append("Tree focus gained\n");
   }
   public void focusLost(FocusEvent fe)
   {
    ta.append("Tree focus lost\n");
   }
  });

  sp.setLeftComponent(new JScrollPane(t));
  JTextField f = new JTextField(10);
  sp.setRightComponent(f);

  pack();

  f.addFocusListener(new FocusListener()
  {
   public void focusGained(FocusEvent fe)
   {
    ta.append("Text field focus gained\n");
   }
    public void focusLost(FocusEvent fe)
{
    ta.append("Text field focus lost\n");
   }
  });
  setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
}
+3
source share
3 answers

setSelectionPath() TreePath node, . DefaultMutableTreeNode. ActionListener , FocusListener - , TreeSelectionListener.

"" node JTree:

JTree tree = new JTree();
TreeNode node = (TreeNode) tree.getModel().getRoot();
node = node.getChildAt(2).getChildAt(1);
TreePath pizza = new TreePath(((DefaultMutableTreeNode) node).getPath());
+2

: EDT, !

JTree t = new JTree();
t.addTreeSelectionListener(new TreeSelectionListener()
{
   public void valueChanged(TreeSelectionEvent tse)
   {
       ta.append("Tree Selection changed\n");
       SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                logicInEDT...(tse);
            }
       });
    }
});

. , .

+1
0

Source: https://habr.com/ru/post/1742911/


All Articles