简体   繁体   English

如何在jlayeredpane Java中画线

[英]how to draw line in jlayeredpane Java

I want to draw line in my jLayeredPane and this is my project from netbeans. 我想在jLayeredPane中画线,这是来自netbeans的项目。

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

I have problem when i clicked my button why i can't draw line in my jlayeredpane??where's my wrong with this code? 我单击按钮时有问题,为什么不能在jlayeredpane中画线?此代码在哪里出错?

I want to draw some line in my jlayeredpane when click button draw.I try to add jlayerpane1.add some component.and i set this for visible. 我想在单击按钮绘制时在我的jlayeredpane中绘制一些线。我尝试添加jlayerpane1.add一些组件。我将此设置为可见。

how to fix it? 如何解决?

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 uses a null layout. JLayeredPane使用空布局。 So when you add your custom painting panel to the layered pane you need to give the panel a size otherwise the size is (0, 0) so there is nothing to paint. 因此,当您将自定义绘画面板添加到分层窗格中时,您需要为面板指定一个大小,否则该大小为(0,0),因此无需进行绘画。

So the code should be something like: 因此,代码应类似于:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM