java - 切换选项卡时在 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 重置为空白?我无法弄清楚这个问题。
解决方案
对您的问题的简短回答是您需要创建一个自定义组件并覆盖该paintComponont
JPanel 等的方法,然后我们可以在该方法中执行我们的自定义绘画。
例如,我们可以创建一个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());
推荐阅读
- perl - 如何使“use strict qw(vars)”对$a和$b生效?
- azure-devops - 在任务中传递 Azure DevOps 管道机密
- audio - UWP 上的 Windows Media Foundation 是否有重采样器?如果是这样,我该如何使用它?
- swift - 为具有泛型类型的对象扩展数组会出错
- sql - 如何将字符串输入转换为“在哪里”
- javascript - 无法检查模态是否打开
- python - matplotlib:添加图像作为注释并旋转它
- swagger-ui - 使用哈希排序的 ApiPlatform Schema 命名
- javascript - 在js中动态创建字段
- haskell - 将列表拆分为 Haskell 中的列表列表