首页 > 解决方案 > 切换选项卡时在 JPanel 上绘图(Net Beans Java Gui 生成器)

问题描述

我有以下代码:

    private void gardenJPanelMouseClicked(java.awt.event.MouseEvent evt) {                                          
        Graphics g = this.gardenJPanel.getGraphics();
        Graphics2D draw = (Graphics2D) g;

        int x = evt.getX();
        int y = evt.getY();
       
        draw.setStroke(new BasicStroke(pointStroke));

        draw.drawLine(x, y, x, y);
    }            

以下代码完美地利用了 JPanel。唯一的问题是切换选项卡时 JPanel 上的图形会重置。切换选项卡时如何防止 JPanel 重置为空白?我无法弄清楚这个问题。

标签: javaswinggraphics

解决方案


对您的问题的简短回答是您需要创建一个自定义组件并覆盖该paintComponontJPanel 等的方法,然后我们可以在该方法中执行我们的自定义绘画。

例如,我们可以创建一个JPanel包含鼠标点击事件的扩展类:

public class MyCustomPanel extends JPanel implements MouseListener 
{
    //If you want to dynamically draw dots then use a list to manage them
    ArrayList<Point> points = new ArrayList<>();
    
    //Here is where the painting happens, we need to override the default paint behaviour, then add our own painting
    @Override
    protected void paintComponent(Graphics g)
    {
        //Call this first to perform default painting (borders etc)
        super.paintComponent(g);
    
        //Here we can add our custem painting
        Graphics2D draw = (Graphics2D) g;
        draw.drawString("Example painting", 10, 10);
    
        //If you want to dynamically draw dots then use a list to manage them:
        for (Point point : points)
        {
            draw.drawLine(point.x, point.y, point.x, point.y);
        }
    }
    
    //Add a new point and refresh the graphics
    @Override
    public void mouseClicked(MouseEvent e)
    {
        points.add(new Point(e.getX(), e.getY()));
        this.repaint();
    }
}

然后插入myCustomPanel我们不使用 UI 生成器,而是可以直接将其添加到 JFrame 中,如下所示:

MyCustomPanel panel = new MyCustomPanel();
yourJFframe.add(new myCustomPanel());

推荐阅读