我创建了 JTree 及其所有组件,然后在另一个类中将其添加到 JPanel。之后,我将 JPanel 添加到 JFrame;是的,我确保所有内容都设置为可见,面板在 setVisible() 之前添加到框架中,等等。
那么为什么我的带有 JTree 的滚动窗格没有出现呢?
package TreeExample;
import java.awt.Color;
import javax.swing.JComponent;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class Tree extends JComponent
{
JTree tree;
JScrollPane scrollPane;
DefaultMutableTreeNode root = new DefaultMutableTreeNode("RootNode");
public Tree()
{
setVisible(true);
setSize(100, 300);
createChildNodes(root);
tree = new JTree(root);
tree.setVisible(true);
tree.setSize(100, 300);
scrollPane = new JScrollPane(tree);
scrollPane.add(tree);
scrollPane.setVisible(true);
scrollPane.setSize(100, 300);
scrollPane.setViewportView(this);
scrollPane.setBackground(Color.red);
}
private void createChildNodes(DefaultMutableTreeNode rootNode)
{
DefaultMutableTreeNode child1 = new DefaultMutableTreeNode("Child 1");
DefaultMutableTreeNode child2 = new DefaultMutableTreeNode("Child 2");
DefaultMutableTreeNode child3 = new DefaultMutableTreeNode("Child 3");
rootNode.add(child1);
rootNode.add(child2);
rootNode.add(child3);
DefaultMutableTreeNode grandchild1 = new DefaultMutableTreeNode(
"Grandchild 1");
DefaultMutableTreeNode grandchild2 = new DefaultMutableTreeNode(
"Grandchild 2");
child1.add(grandchild1);
child1.add(grandchild2);
}
}
这是我的面板...
package TreeExample;
import java.awt.BorderLayout;
import java.awt.TextArea;
import javax.swing.JPanel;
public class Panel extends JPanel
{
Panel()
{
setLayout(new BorderLayout());
add(new Toolbar(), BorderLayout.NORTH);
add(new TextArea(), BorderLayout.CENTER);
add(new Tree(), BorderLayout.WEST);
}
}
这是我的框架。
package TreeExample;
import javax.swing.JFrame;
public class Frame extends JFrame
{
Frame()
{
setTitle("ToolBar Example");
add(new Panel());
pack();
setVisible(true);
setSize(500, 500);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args)
{
new Frame();
}
}