gpt4 book ai didi

java - 如何在 jlayeredpane Java 中画线

转载 作者:行者123 更新时间:2023-12-01 11:11:46 26 4
gpt4 key购买 nike

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

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

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

当单击绘制按钮时,我想在 jlayeredpane 中画一些线。我尝试添加 jlayerpane1。添加一些组件。并将其设置为可见。

如何解决?

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
}

最佳答案

JLayeredPane 使用空布局。因此,当您将自定义绘画面板添加到分层 Pane 时,您需要为面板指定一个大小,否则大小为 (0, 0),因此没有任何内容可绘制。

所以代码应该是这样的:

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

关于java - 如何在 jlayeredpane Java 中画线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32270528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com