Reputation: 59
I want to draw line in my jLayeredPane and this is my project from netbeans.
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?
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.
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
}
Upvotes: 0
Views: 377
Reputation: 324108
A JLayeredPane
uses a null layout. 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.
So the code should be something like:
JPanel panel = new CustomPaintingPanel();
panel.setSize(300, 300);
layeredPane.add(panel, ...);
frame.add(layeredPane);
Upvotes: 1