如何从一个jpanel到另一个jpanel画一条线

我有两个 JPanel,我想单击第一个面板,然后单击第二个面板,并在两个面板之间绘制一条直线。此外,放置后,该线必须保留在两个面板之间。有人可以告诉我从哪里开始吗?这两个面板放置在第三个面板上,它们是下图中的蓝色矩形。先感谢您。

http://img4.mukewang.com/64af9319000113db06480289.jpg

父 JPanel


import javax.swing.*;

import java.awt.*;

import java.util.ArrayList;



            class WorkflowPanel extends JPanel {

                private volatile int screenX = 0;

                private volatile int screenY = 0;

                private static final int RADIUS = 35;

                private int radius = RADIUS;

                private ArrayList<ModelView> relationship;

                WorkflowPanel() {

                    relationship = new ArrayList<>();

                    relationship.add(new ModelView());

                    relationship.add(new ModelView());

                    add(relationship.get(0));

                    add(relationship.get(1));

                    setLayout(null);

                    setVisible(true);

                }


                @Override

                protected void paintChildren(Graphics g) {

                        for (int i = 0; i < relationship.size(); i += 2) {

                        ModelView one = relationship.get(i);

                        ModelView two = relationship.get(i + 1);

                        Point p1 = new Point(one.getLocation().x + one.getWidth() / 2, one.getLocation().y + one.getHeight() / 2);

                        Point p2 = new Point(two.getLocation().x + two.getWidth() / 2, two.getLocation().y + two.getHeight() / 2);

                        g.drawLine(p1.x, p1.y, p2.x, p2.y);

                        this.repaint();

                    }

                    super.paintChildren(g);

                }



                public ArrayList<ModelView> getRelationship() {

                    return relationship;

                }

            }


梦里花落0921
浏览 75回答 1
1回答

POPMUISE

有人可以告诉我从哪里开始吗?父面板需要知道子面板之间的关系。一种方法是保持跟踪ArrayList组件对之间的关系。然后,您需要重写paintChildren(...)父面板的方法以在两个子面板之间绘制一条线。您在父面板类中定义 ArrayList:private ArrayList<Component> relationships = new ArrayList<Component>();然后根据需要将组件对添加到 ArrayList:relationships.add( component1a );relationships.add( component1b );基本的绘画代码是:@Overrideprotected void paintChildren(Graphics g){&nbsp; &nbsp; for (int i = 0; i < relationships.size(); i += 2)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Component one = relationships.get(i);&nbsp; &nbsp; &nbsp; &nbsp; Component two = relationships.get(i + 1);&nbsp; &nbsp; &nbsp; &nbsp; Point p1 = //calculate the center of component one&nbsp; &nbsp; &nbsp; &nbsp; Point p2 = //calculate the center of component two&nbsp; &nbsp; &nbsp; &nbsp; g.drawline(p1.x, p1.y, p2.x, p2.y);&nbsp; &nbsp; }&nbsp; &nbsp; super.paintChildren(g);}因此,上面的代码应该在添加到 ArrayList 的每对组件的中心点之间绘制线条。然后,子面板将绘制在线条的顶部,以便线条看起来像是从每个组件的边缘出来的。查看trashgod 的GraphPanel示例。此示例支持拖动形状,并且线条将跟随形状。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java