首页 > 解决方案 > 一般jframe中如何使用多个jpanel

问题描述

我将可视化聚类分析 k-means 的实现,为此我使用 swing。存在一个问题,即添加的第二个 jpanel (nodePanel) 没有像集群发生的那样被处理。

我尝试处理 jframe 和 jpanel 类,据我所知,它不能在多线程级别解决,但后来我在实现这个想法时遇到了困难。

public class MainUI extends JFrame {
    JPanel canvas;
    NodePanel nodePanel;
    ClusterPanel clusterPanel;
    public static boolean isPaintCluster;
    MainUI(String title) {
        super(title);
        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        init();
        super.setSize(700, 540);
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension frm = super.getSize();
        int xpos = (int) (screen.getWidth() / 2 - frm.getWidth() / 2);
        int ypos = (int) (screen.getHeight() / 2 - frm.getWidth() / 2);
        super.setLocation(xpos, ypos);
        super.setVisible(true);
    }
    void init(){
        this.setLayout(null);
        canvas = new JPanel();
        nodePanel = new NodePanel();
        clusterPanel = new ClusterPanel();
        nodePanel.addMouseListener(new NodeClickListener(nodePanel));
     clusterPanel.addMouseListener(new ClusterClickListener(clusterPanel));
        canvas.setBackground(Color.white);
        canvas.setBounds(10,10,480,480);
        nodePanel.setBounds(10,10,480,480);
        clusterPanel.setBounds(10,10,480,480);
        this.add(canvas);
        this.add(clusterPanel);
        this.add(nodePanel);
        JPanel ButtonPanel = new JPanel();
        JRadioButton radioButtonNodes = new JRadioButton("add Nodes");
        radioButtonNodes.addActionListener(new isPaintNode());
        JRadioButton radioButtonCluster = new JRadioButton("add Clusters");
        radioButtonCluster.addActionListener(new isPaintCluster());
        ButtonPanel.setLayout(null);
        this.add(ButtonPanel);
        ButtonPanel.setBounds(500,10,180,480);
        ButtonPanel.add(radioButtonNodes);
        radioButtonNodes.setBounds(0,200,120,20);
        ButtonPanel.add(radioButtonCluster);
        radioButtonCluster.setBounds(0,230,120,20);
    }

    class isPaintCluster implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(isPaintCluster){isPaintCluster = false;}
            else {isPaintCluster = true;}
        }
    }
    class isPaintNode implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            if(isPaintNode){isPaintNode = false;}
            else {isPaintNode = true;}
        }
    }
}

我希望得到一个解决方案,其中集群和节点将作为端类独立,但是在学习的每一步的应用程序中,集群的位置将被重新定义,节点的颜色也会根据集群。

标签: javaswingjframejpanel

解决方案


我没有想到比将 NodePanel 和 СlusterPanel 类组合成一个类来处理表单中添加的节点和集群更好的方法。


推荐阅读