java树组件JTree的用法,要求详解啊!!
发布网友
发布时间:2023-10-14 13:47
我来回答
共1个回答
热心网友
时间:2024-11-23 03:36
树都是由节点组成的.并且一颗树只有一个根节点,下面是代码运行的javapackage demo1;import java.awt.Toolkit;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.Dimension;public class Application1 {
boolean packFrame = false; /**
* Construct and show the application.
*/
public Application1() {
Frame1 frame = new Frame1();
// Validate frames that have preset sizes
// Pack frames that have useful preferred size info, e.g. from their layout
if (packFrame) {
frame.pack();
}
else {
frame.validate();
} // Center the window
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = frame.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}
frame.setLocation( (screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
frame.setVisible(true);
} /**
* Application entry point.
*
* @param args String[]
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
}
catch (Exception exception) {
exception.printStackTrace();
} new Application1();
}
});
}
}package demo1;
import java.awt.Toolkit;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import java.awt.Dimension;
import java.awt.*;
import javax.swing.*;
import java.awt.Dimension;
import java.awt.Rectangle;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.BorderFactory;public class Frame1
extends JFrame {
JPanel contentPane;
JPanel jPanel1 = new JPanel();
JTree jTree1;
BorderLayout borderLayout1 = new BorderLayout();
public Frame1() {
try {
setDefaultCloseOperation(EXIT_ON_CLOSE);
jbInit();
}
catch (Exception exception) {
exception.printStackTrace();
}
} /**
* Component initialization.
*
* @throws java.lang.Exception
*/
private void jbInit() throws Exception {
contentPane = (JPanel) getContentPane();
contentPane.setLayout(null);
setSize(new Dimension(465, 380));
setTitle("Frame Title");
jPanel1.setBorder(BorderFactory.createEtchedBorder());
jPanel1.setBounds(new Rectangle(37, 12, 216, 317));
jPanel1.setLayout(borderLayout1);
contentPane.add(jPanel1);
DefaultMutableTreeNode root=new DefaultMutableTreeNode("根节点");
DefaultMutableTreeNode r1=new DefaultMutableTreeNode("子节点");
DefaultMutableTreeNode r01=new DefaultMutableTreeNode("子节点下的节点");
DefaultMutableTreeNode r2=new DefaultMutableTreeNode("子节点2");
DefaultMutableTreeNode r3=new DefaultMutableTreeNode("子节点三");
// 向根节点中添加子节点
root.add(r1);
root.add(r2);
r1.add(r01);
root.add(r3);
jTree1=new JTree(root);
jPanel1.add(jTree1, java.awt.BorderLayout.NORTH);
//传入根节点
this.setVisible(true);
this.setBounds(100,100,400,500); }
public static void main(String[] args) {
Frame1 f=new Frame1();
}
}