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。添加一些组件。我把它设为可见。
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
}
1 个解决方案
#1
1
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.
JLayeredPane使用空布局。所以当你将自定义的绘图面板添加到层叠的面板中时,你需要给面板一个尺寸,否则面板的尺寸是(0,0)所以没有什么可画的。
So the code should be something like:
所以代码应该是这样的:
JPanel panel = new CustomPaintingPanel();
panel.setSize(300, 300);
layeredPane.add(panel, ...);
frame.add(layeredPane);
#1
1
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.
JLayeredPane使用空布局。所以当你将自定义的绘图面板添加到层叠的面板中时,你需要给面板一个尺寸,否则面板的尺寸是(0,0)所以没有什么可画的。
So the code should be something like:
所以代码应该是这样的:
JPanel panel = new CustomPaintingPanel();
panel.setSize(300, 300);
layeredPane.add(panel, ...);
frame.add(layeredPane);