如何在 jlayeredpane 中画线 Java

how to draw line in jlayeredpane Java

我想在我的 jLayeredPane 中画线 这是我的 netbeans 项目。

https://drive.google.com/file/d/0B6e6jjVl5-sCMkJFcEI3MkZEZ1E/view

我在单击按钮时遇到问题,为什么我无法在我的 jlayeredpane 中画线?这段代码哪里出了问题?

我想在单击按钮时在我的 jlayeredpane 中画一些线 draw.I 尝试添加 jlayerpane1.add 一些 component.and 我将其设置为可见。

如何解决?

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    jLayeredPane1.add(new JComponent(){                                   
     ArrayList<Shape> linesList = new ArrayList<Shape>();
    private Shape line = null;
    {
    MouseAdapter mouseAdapter = new MouseAdapter(){
                @Override
        public void mousePressed (MouseEvent e){                       
        line = new Line2D.Double(e.getPoint(), e.getPoint());
        linesList.add(line);
        repaint();
        }
                @Override
        public void mouseDragged(MouseEvent e){
        Line2D shape =(Line2D)line;
        shape.setLine(shape.getP1(), e.getPoint());
        repaint();
        }
                @Override
        public void mouseReleased(MouseEvent e){
        line = null;
        repaint();
        }
    };
    addMouseListener(mouseAdapter);
    addMouseMotionListener(mouseAdapter);
    }
        @Override
    protected void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D) g;
    g2d.setPaint(Color.BLUE);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    for(Shape content : linesList){
        g2d.draw(content);
    }
  }          
    });
    jLayeredPane1.setVisible(true); // set for visible
}

A JLayeredPane 使用空布局。因此,当您将自定义绘画面板添加到分层窗格时,您需要为面板指定一个尺寸,否则尺寸为 (0, 0),因此没有可绘制的内容。

所以代码应该是这样的:

JPanel panel = new CustomPaintingPanel();
panel.setSize(300, 300);
layeredPane.add(panel, ...);
frame.add(layeredPane);