0

I tried to add an ability of browsing files to my program. I wanted to use code from here: 1 (Gilbert's answer), but that was important to me to have JTree in certain position and size. Unfortunately, when I did this, the JTree doesn't "respond" when I click on it.

Here's the code:

public class Frame extends JFrame implements Runnable {

private DefaultMutableTreeNode root;

private DefaultTreeModel treeModel;

private JTree tree;
public File fileRoot;

public Frame(){
    super("FileBrowser");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    setSize(480, 320);
    setLocation(50,50);
    getContentPane().setLayout(null);

    fileRoot = new File("C:/");
    root = new DefaultMutableTreeNode(new FileNode(fileRoot));
    treeModel = new DefaultTreeModel(root);

    tree = new JTree(treeModel);

    tree.setBounds(10, 39, 155, 177);
    getContentPane().add(tree);
    tree.setShowsRootHandles(true);

}


@Override
public void run() {
    CreateChildNodes ccn = new CreateChildNodes(fileRoot, root);
    new Thread(ccn).start();
}

}

Main class:

public class main {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Frame());
    }
}

When I comment

getContentPane().setLayout(null);

and let JTree fill whole Frame, it works as it should

Community
  • 1
  • 1
Ch0mik18
  • 1
  • 1

1 Answers1

1

Try to change the following lines:

tree.setBounds(10, 39, 155, 177);
getContentPane().add(tree);

to

JScrollPane scroller = new JScrollPane(tree);
scroller.setBounds(10, 39, 155, 177);
getContentPane().add(scroller);

If my proposal has no effect, try to create a SSCCE, so I can see what's wrong.

P.S. Try to learn layout managers. They are very usefull.

Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48
  • Thank You, it works! I know that generally, it's far better to use layout managers, but in my case, i want to display my program on certain screen, and layout isn't the key feature, so I chose the easier way. – Ch0mik18 Jul 14 '16 at 13:06
  • 1
    To expand on the thing in that answer **most** worth paying attention to: Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Jul 14 '16 at 14:11
  • @Ch0mik18 in this case it would nice if you accept my answer as correct. – Sergiy Medvynskyy Jul 14 '16 at 14:24