ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Java JApplet:按钮树问题

2019-12-08 01:03:27  阅读:319  来源: 互联网

标签:jtree japplet button swing java


此小程序应采用存储在menuTree中的树,并基于该树进行菜单构建.

currentNode存储小程序当前所在的菜单,并且其每个子级都应显示为按钮.

单击按钮后,小程序将带您进入一个新菜单,代表单击的按钮.

我无法让按钮在单击另一个按钮时发生变化.

我不确定这棵树是否正确构建,因为它不是特别容易测试.

任何帮助将不胜感激.

谢谢.

import javax.swing.*;
import javax.swing.tree.*;
import java.awt.event.*;
import java.awt.*;

public class Menu extends JApplet implements ActionListener{
    private static final long serialVersionUID = 2142470002L;
    private JTree menuTree;
    private DefaultMutableTreeNode currentNode;
    private JPanel buttonPanel;

    public void init(){
        this.setSize(700, 550);
        buttonPanel=new JPanel();
        buttonPanel.setSize(300, 500);
        this.add(buttonPanel);

        /**
         * will make node out of the first entry in the array, then make nodes out of subsequent entries
         * and make them child nodes of the first one. The process is  repeated recursively for entries that are arrays.
         * this idea of tree declaration as well as the code from the method was lovingly
         * stolen from: http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JTree.html
         */
        Object [] menuNames =   { "ROOT",
                                    new Object[] { "Classic Chess",
                                        new Object[] { "Game",
                                            "AI",
                                            "Hotseat",
                                            "Online"
                                        },
                                        "Challenges",
                                        new Object[]{ "Practice",
                                            "Situations",
                                            "Coaching"
                                        },
                                    },
                                    new Object[] { "Fairy Chess",
                                        new Object[] { "Game",
                                            "AI",
                                            "Hotseat",
                                            "Online"
                                        },
                                        "Challenges",
                                        new Object[]{ "Practice",
                                            "Situations",
                                            "Coaching"
                                        },
                                        "Create Pieces"
                                    }
                                };

        currentNode=processHierarchy(menuNames);
        menuTree = new JTree(currentNode);
        initializeButtons(currentNode);
    }


    /**
     * Clicking one of the buttons(which should be in the children of the currentNode), takes you to that node in the tree
     *      setting currentNode to that node and redoing buttons to represent its children.
     */
    public void actionPerformed(ActionEvent ae){
        Button b=(Button)ae.getSource();
        for(int i =0; i<currentNode.getChildCount(); i++){
            if(b.getLabel().equals(currentNode.getChildAt(i)+"")){
                currentNode=(DefaultMutableTreeNode)currentNode.getChildAt(i);
                initializeButtons(currentNode);
            }
        }
    }


    /**
     * will make node out of the first entry in the array, then make nodes out of subsequent entries
     * and make them child nodes of the first one. The process is  repeated recursively for entries that are arrays.
     * this idea of tree declaration as well as the code from the method was lovingly
     * stolen from: http://www.apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JTree.html
     */
    private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]);
        DefaultMutableTreeNode child;
        for (int i = 1; i < hierarchy.length; i++) {
            Object nodeSpecifier = hierarchy[i];
            if (nodeSpecifier instanceof Object[]) // Ie node with children
                child = processHierarchy((Object[]) nodeSpecifier);
            else
                child = new DefaultMutableTreeNode(nodeSpecifier); // Ie Leaf
            node.add(child);
        }
        return (node);
    }


    /**
     * creates buttons for each child of the given node, labels them with their String value, and adds them to the panel.
     */
    private void initializeButtons(DefaultMutableTreeNode node){
        Button b;
        buttonPanel.removeAll();
        for(int i =0; i<node.getChildCount(); i++){
            b=new Button();
            b.setLabel(""+node.getChildAt(i));
            buttonPanel.add(b);
        }
    }

}

解决方法:

遵循@Andrew的有用概述,TreeSelectionListener似乎很合适.有关详细信息,请参见How to Use Trees.应用程序似乎更容易调试.使用revalidate()是更新修订版式的关键.

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Container;
import java.awt.EventQueue;
import java.awt.GridLayout;
import javax.swing.JApplet;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

/** @see https://stackoverflow.com/questions/7342713 */
public class Menu extends JApplet {

    private JTree menuTree;
    private JPanel buttonPanel;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setTitle("Menu");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                new Menu().initContainer(frame);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    @Override
    public void init() {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                initContainer(Menu.this);
            }
        });
    }

    private void initContainer(Container container) {
        container.setLayout(new GridLayout(1, 0));
        buttonPanel = new JPanel(new GridLayout(0, 1));
        Object[] menuNames = {"ROOT",
            new Object[]{"Classic Chess",
                new Object[]{"Game", "AI", "Hotseat", "Online"},
                "Challenges",
                new Object[]{"Practice", "Situations", "Coaching"}
            },
            new Object[]{"Fairy Chess",
                new Object[]{"Game", "AI", "Hotseat", "Online"},
                "Challenges",
                new Object[]{"Practice", "Situations", "Coaching"},
                "Create Pieces"
            }
        };

        DefaultMutableTreeNode currentNode = processHierarchy(menuNames);
        menuTree = new JTree(currentNode);
        menuTree.setVisibleRowCount(10);
        menuTree.expandRow(2);
        initializeButtons(currentNode);
        container.add(buttonPanel, BorderLayout.WEST);
        container.add(new JScrollPane(menuTree), BorderLayout.EAST);
        menuTree.addTreeSelectionListener(new TreeSelectionListener() {

            @Override
            public void valueChanged(TreeSelectionEvent e) {
                initializeButtons((DefaultMutableTreeNode)
                    menuTree.getLastSelectedPathComponent());
            }
        });
    }

    private DefaultMutableTreeNode processHierarchy(Object[] hierarchy) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(hierarchy[0]);
        DefaultMutableTreeNode child;
        for (int i = 1; i < hierarchy.length; i++) {
            Object nodeSpecifier = hierarchy[i];
            if (nodeSpecifier instanceof Object[]) {
                child = processHierarchy((Object[]) nodeSpecifier);
            } else {
                child = new DefaultMutableTreeNode(nodeSpecifier);
            }
            node.add(child);
        }
        return (node);
    }

    private void initializeButtons(DefaultMutableTreeNode node) {
        Button b;
        buttonPanel.removeAll();
        for (int i = 0; i < node.getChildCount(); i++) {
            b = new Button();
            b.setLabel("" + node.getChildAt(i));
            buttonPanel.add(b);
            buttonPanel.revalidate();
        }
    }
}

标签:jtree,japplet,button,swing,java
来源: https://codeday.me/bug/20191208/2087856.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有