我发现在记录选定的路径后,如果在展开之前重置选择,速度会非常快。
final TreePath[] paths = tree.getSelectionPaths();
//Modifying the selection makes it run a whole lot faster
tree.setSelectionPath(paths[0]);
for(int i = 0; i < paths.length; i++){
tree.expandPath(paths[i]);
}
我认为这是因为它不再需要对选择做太多的魔法了。
由于害怕被打死,我会提供这个建议。如果您想在此过程中保持 GUI 解锁状态,您可以将其扔到一个新线程上(而不是在 EDT 上)。当然,您必须非常小心,不要尝试与 Tree 进行交互 - Swing 不是线程安全的,因此除了查看它之外的任何其他操作都会导致各种时髦的问题。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
public class JTreeExpanding extends Box{
//Just to make sure no user interactions happen during expansion
JPanel glassPane = new JPanel(){
public void paintComponent(Graphics g){
g.setColor(new Color(0,0,0,80));
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(Color.white);
g.setFont(g.getFont().deriveFont(18f).deriveFont(Font.BOLD));
g.drawString("Processing...", getWidth()-100, getHeight()-10);
}
};
public JTreeExpanding(){
super(BoxLayout.Y_AXIS);
glassPane.setOpaque(false);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
for(int i = 0; i < 14000; i++){
DefaultMutableTreeNode node = new DefaultMutableTreeNode("Root" + i);
node.add(new DefaultMutableTreeNode("Child" + i));
root.add(node);
}
final JTree tree = new JTree(root);
tree.setRootVisible(false);
final JScrollPane pane = new JScrollPane(tree);
add(pane);
JButton button = new JButton("Expand");
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
//Taking the expand off the EDT frees up GUI
Thread t = new Thread(new Runnable(){
@Override
public void run() {
final TreePath[] paths = tree.getSelectionPaths();
//Modifying the selection makes it run a whole lot faster
tree.setSelectionPath(paths[0]);
for(int i = 0; i < paths.length; i++){
tree.expandPath(paths[i]);
}
glassPane.setVisible(false);
}});
getRootPane().setGlassPane(glassPane);
glassPane.setVisible(true);
t.start();
}});
add(button);
//Allow Scrolling in scroll pane while Tree is expanding
glassPane.addMouseWheelListener(new MouseWheelListener() {
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
for(MouseWheelListener mwl : pane.getMouseWheelListeners()){
mwl.mouseWheelMoved(e);
}
}
});
}
public static void main(String[] args) {
// TODO Auto-generated method stub
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new JTreeExpanding());
frame.validate();
frame.pack();
frame.setVisible(true);
}
}