当您单击每个树节点时,我想将信息添加到jpanel jscrollpane中 [英] I would like to put the information to add in jpanel jscrollpane when you click each tree node

查看:76
本文介绍了当您单击每个树节点时,我想将信息添加到jpanel jscrollpane中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您单击每个树节点时,我想将信息添加到jpanel jscrollpane中...请... !!!

I would like to put the information to add in jpanel jscrollpane when you click each tree node... Please...!!!

1.我想在Tree.java中控制该状态的选定树节点,其中Frame.java

1.I want to control that state selected tree node at Tree.java where Frame.java

Tree.java

Tree.java

package pms;
import java.awt.BorderLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

public class Tree extends JTree {
private JTree tree;
public static int selectItem = 0;

public JTree CreateTree() {
    setLayout(new BorderLayout());
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Management");
    DefaultMutableTreeNode bigLeaf1 = new DefaultMutableTreeNode("Generl Affair");
    DefaultMutableTreeNode bigLeaf2 = new DefaultMutableTreeNode("Personal Affair");
    final DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Recruit");
    final DefaultMutableTreeNode leaf3 = new DefaultMutableTreeNode("test");

    bigLeaf1.add(leaf2);
    bigLeaf2.add(leaf3);
    root.add(bigLeaf1);
    root.add(bigLeaf2);
    tree = new JTree(root);

    tree.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            TreePath tp = tree.getPathForLocation(e.getX(), e.getY());
            if (e.getClickCount() >= 2) {
                if (tp.getLastPathComponent() == leaf2) {
                    selectItem = 2;
                    System.out.println(selectItem);
                } else if (tp.getLastPathComponent() == leaf3) {
                    selectItem = 3;
                    System.out.println(selectItem);
                }
            }
        }
    });

    return tree;
    }

    public int selectedItem() {
        return selectItem;
    }
}

Frame.java

Frame.java

package pms;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public class Frame extends JFrame implements Runnable {
    static int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
    static int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
    private JPanel pan1, pan2, pan3, pan4;
    public static JScrollPane jsp2;
    public Tree tree;
    public static ArrayList<Viewer> ViewArr = new ArrayList<Viewer>();
    public static int selectItem = 0;

    public Frame() {
        setTitle("Personal Management System");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        getContentPane().setLayout(null); // AbsoulteLayout

        /** Create MenuBar */
        menuBar menubar = new menuBar();
        setJMenuBar(menubar.CreateMenuBar());

        pan1 = new JPanel(new GridLayout()); // TreeNode ScrollPane
        pan2 = new JPanel(new BorderLayout()); // toolbar & ScrollPane2
        pan1.setBounds(0, 0, 350, 950); // Fixed Panel Size
        pan2.setBounds(350, 0, 1300, 950);
        getContentPane().add(pan1);
        getContentPane().add(pan2);

        /** Create Tree */
        tree = new Tree();

        JScrollPane jsp1 = new JScrollPane(tree.CreateTree(), v, h);
        pan1.add(jsp1);

        /** Create toolbar Panel */
        pan3 = new toolBar().CreateToolbar();
        pan2.setLayout(new BorderLayout());
        pan2.add(pan3, "North");

        /** Create viewer ScrollPane */
        jsp2 = new JScrollPane(v, h);
        jsp2.setBackground(Color.cyan);

        pan2.add(jsp2, "East");
        setSize(1300, 950);
        setVisible(true);
    }

    public void ShowInterViewer() {
        selectItem = tree.selectedItem();
        try {
            if (selectItem == 2) {
                System.out.println("222");
            } else if (selectItem == 3) {
                System.out.println("333");
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.run();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
            }
        });
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        ShowInterViewer();
    }
}

Viewer.java

Viewer.java

    package pms;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Date;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class Viewer extends JPanel implements ActionListener{
    private JPanel jp;
    private JTextField tf1, tf2, tf3, tf4, tf5, tf6;
    private JLabel lb1, lb2, lb3, lb4, lb5, lb6;
    private JButton btn1;
    private String name, sex, pass, phone, picturePath, filePath;
    private Date birthday, interviewDate;

    public Viewer(String name, Date birthday, String sex, Date interviewDate, String pass, String phone) {
        setName(name);
        setSex(sex);
        setPass(pass);
        setPass(pass);
        CreateViewer();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        if(sex.equals("M")){
            this.sex = "남자";
        }else if(sex.equals("W")){
            this.sex = "여자";
        }
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        if(pass.equals("Y")){
            this.pass = "합격";
        }else if(pass.equals("N")){
            this.pass = "불합격";
        }
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getPicturePath() {
        return picturePath;
    }

    public void setPicturePath(String picturePath) {
        this.picturePath = picturePath;
    }

    public String getFilePath() {
        return filePath;
    }

    public void setFilePath(String filePath) {
        this.filePath = filePath;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public Date getInterviewDate() {
        return interviewDate;
    }

    public void setInterviewDate(Date interviewDate) {
        this.interviewDate = interviewDate;
    }

    public JPanel CreateViewer(){
        jp = new JPanel(new BorderLayout());

        tf1 = new JTextField(getName());
        tf1.setColumns(20);
        //tf1.setBounds(50,50,10,10);
        tf2 = new JTextField();
        tf2.setColumns(20);
        tf3 = new JTextField();
        tf3.setColumns(20);
        tf4 = new JTextField();
        tf4.setColumns(20);
        tf5 = new JTextField();
        tf5.setColumns(20);
        tf6 = new JTextField();
        tf6.setColumns(20);

        lb1 = new JLabel("이름");
        lb2 = new JLabel("생년월일");
        lb3 = new JLabel("성별");
        lb4 = new JLabel("면접일자");
        lb5 = new JLabel("합격여부");
        lb6 = new JLabel("연락처");

        btn1 = new JButton("이력서 보기");



        jp.add(tf1);
        jp.add(tf2);
        jp.add(tf3);
        jp.add(tf4);
        jp.add(tf5);
        jp.add(tf6);
        jp.add(lb1);
        jp.add(lb2);
        jp.add(lb3);
        jp.add(lb4);
        jp.add(lb5);
        jp.add(lb6);
        jp.add(btn1);

        return jp;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub

    }
}

推荐答案

首先,您真的不需要扩展JTree,也无需向该类添加任何新功能(实际上,您也没有使用它),只需创建JTree的实例,然后将实例传递给TreeModel即可为您的数据建模.

First of all, you really don't need to extend a JTree, you're not adding any new functionality to the class (nor are you actually using it), instead, just create an instance of JTree and pass it an instance a TreeModel which models your data.

这意味着您可以自由地在JTree上添加TreeListSelection,这将告诉您选择的更改时间.从生成的TreeSelectionEvent中,您可以获取所选的path,这将告诉您从根到当前所选节点中选择的组件.然后,您可以使用getLastPathComponent获取路径中的最后一个节点(将是所选节点).

This means that you are free to add a TreeListSelection to the JTree, which will tell you when the selection changes. From the resulting TreeSelectionEvent you can get the selected path, which will tell you the components which are selected from the root to the currently selected node. You can then use getLastPathComponent to get the last node in the path (which will be the selected node).

一旦有了这些信息,就可以决定如何最好地将其提供给相应的视图.因为您使用的是DefaultMutableTreeNode,所以可以将userObject与它关联,这样可以更轻松地在每个节点上存储复杂的数据.

Once you have this information, you can then make decisions about how best you should feed it to the corresponding view. Because you're using DefaultMutableTreeNode, you can associate a userObject with it, which makes it easier to store complex data with each node.

基于您的Viewer类,似乎数据非常普通化,在这种情况下,我将考虑创建POJO来维护所有相关数据并将其简单地应用于DefaultMutableTreeNode,这样您就可以使用getUserObject轻松提取它.然后,您只需将该对象(通过某种设置器)传递给Viewer面板,并让查看者相应地更新其自身状态

Based on your Viewer class, it would seem that the data is pretty commonailised, in that case I would consider creating POJO which maintains all the associated data and simply apply it to the DefaultMutableTreeNode, this way you can use getUserObject to extract it easily. You then simply pass this object to the Viewer panel (via some kind of setter) and let the viewer update it's own state accordingly

看看如何使用树更多详情

例如...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.text.DateFormat;
import java.time.LocalDate;
import java.time.Month;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

public class InterviewBrowser {

    public static void main(String[] args) {
        new InterviewBrowser();
    }

    public InterviewBrowser() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                DefaultMutableTreeNode root = new DefaultMutableTreeNode("Management");
                DefaultMutableTreeNode bigLeaf1 = new DefaultMutableTreeNode("Generl Affair");
                DefaultMutableTreeNode bigLeaf2 = new DefaultMutableTreeNode("Personal Affair");
                DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode(new InterviewHistory(
                                "Bob",
                                new Date(LocalDate.of(1972, Month.MARCH, 8).toEpochDay()),
                                Sex.MALE,
                                new Date(LocalDate.of(2015, Month.AUGUST, 10).toEpochDay()),
                                false,
                                "123456789"));
                DefaultMutableTreeNode leaf3 = new DefaultMutableTreeNode(new InterviewHistory(
                                "Jane",
                                new Date(LocalDate.of(1973, Month.JANUARY, 1).toEpochDay()),
                                Sex.FEMALE,
                                new Date(LocalDate.of(2015, Month.AUGUST, 10).toEpochDay()),
                                true,
                                "87654321"));

                bigLeaf1.add(leaf2);
                bigLeaf2.add(leaf3);
                root.add(bigLeaf1);
                root.add(bigLeaf2);
                DefaultTreeModel model = new DefaultTreeModel(root);

                JTree tree = new JTree(model);

                Viewer viewer = new Viewer();

                tree.addTreeSelectionListener(new TreeSelectionListener() {
                    @Override
                    public void valueChanged(TreeSelectionEvent e) {
                        TreePath path = e.getPath();
                        Object lastPathComponent = path.getLastPathComponent();
                        if (lastPathComponent instanceof DefaultMutableTreeNode) {
                            DefaultMutableTreeNode node = (DefaultMutableTreeNode) lastPathComponent;
                            Object userObject = node.getUserObject();
                            if (userObject instanceof InterviewHistory) {
                                InterviewHistory history = (InterviewHistory) userObject;
                                viewer.setHistory(history);
                            } else {
                                viewer.setHistory(null);
                            }
                        } else {
                            viewer.setHistory(null);
                        }
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new JScrollPane(tree), BorderLayout.WEST);
                frame.add(viewer);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public enum Sex {

        MALE,
        FEMALE
    }

    public class InterviewHistory {

        private String name;
        private Date birthDate;
        private Sex sex;
        private Date interviewDate;
        private boolean passed;
        private String phone;

        public InterviewHistory(String name, Date birthDate, Sex sex, Date interviewDate, boolean passed, String phone) {
            this.name = name;
            this.birthDate = birthDate;
            this.sex = sex;
            this.interviewDate = interviewDate;
            this.passed = passed;
            this.phone = phone;
        }

        public String getName() {
            return name;
        }

        public Date getBirthDate() {
            return birthDate;
        }

        public Sex getSex() {
            return sex;
        }

        public Date getInterviewDate() {
            return interviewDate;
        }

        public boolean didPass() {
            return passed;
        }

        public String getPhone() {
            return phone;
        }

        @Override
        public String toString() {
            return getName();
        }

    }

    public static class Viewer extends JPanel {

        public static final DateFormat DATE_FORMAT = DateFormat.getDateInstance();

        private JTextField name;
        private JTextField dateOfBirth;
        private JLabel sex;
        private JTextField dateOfInterview;
        private JCheckBox passed;
        private JTextField phone;

        public Viewer() {
            setLayout(new GridBagLayout());

            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridx = 0;
            gbc.gridy = 0;
            gbc.anchor = GridBagConstraints.WEST;

            add(new JLabel("Name: "), gbc);
            gbc.gridy++;
            add(new JLabel("Date of birth: "), gbc);
            gbc.gridy++;
            add(new JLabel("Sex: "), gbc);
            gbc.gridy++;
            add(new JLabel("Date of Interview: "), gbc);
            gbc.gridy++;
            add(new JLabel("Passed interview: "), gbc);
            gbc.gridy++;
            add(new JLabel("Phone: "), gbc);

            name = new JTextField(25);
            dateOfBirth = new JTextField(10);
            sex = new JLabel("?");
            dateOfInterview = new JTextField(10);
            passed = new JCheckBox();
            phone = new JTextField(9);

            gbc.gridx++;
            gbc.gridy = 0;

            add(name, gbc);
            gbc.gridy++;
            add(dateOfBirth, gbc);
            gbc.gridy++;
            add(sex, gbc);
            gbc.gridy++;
            add(dateOfInterview, gbc);
            gbc.gridy++;
            add(passed, gbc);
            gbc.gridy++;
            add(phone, gbc);

        }

        public void setHistory(InterviewHistory history) {
            name.setText(history == null ? null : history.getName());
            dateOfBirth.setText(history == null ? null : DATE_FORMAT.format(history.getBirthDate()));
            sex.setText(history == null ? "?" : history.getSex().name());
            dateOfInterview.setText(history == null ? null : DATE_FORMAT.format(history.getInterviewDate()));
            passed.setSelected(history == null ? false : history.didPass());
            phone.setText(history == null ? "?" : history.getPhone());
        }

    }
}

不要依赖static变量的状态,可以轻松地使该状态不反映现实,而要依靠可以从视图/模型的状态确定的实际已知值.

DO NOT rely on the state of static variables, it is WAY to easy for that state not to reflect reality, instead, rely on actual known values you can ascertain from the state of the view/model.

任何模型的目的都是为您提供一种显示数据的机制,您应该使用它直接包装数据,而不是尝试猜测UI或模型的状态,然后分别查找数据(恕我直言)

The purpose of any model is to provide a mechanism for you to display your data, you should use it to wrap your data directly, rather the trying to guess at the state of the UI or model and then look up the data separately (IMHO)

这篇关于当您单击每个树节点时,我想将信息添加到jpanel jscrollpane中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆