【问题标题】:Can't paint on JPanel after clearRect() and repaint()clearRect() 和 repaint() 后无法在 JPanel 上绘画
【发布时间】:2015-05-10 04:12:22
【问题描述】:

我有一个让用户绘画的程序。但是当用户单击调用 clearRect() 和 repaint() 的清除按钮时,用户不能再继续在同一个面板上绘画。我遇到的另一个问题是,当用户单击保存或打开按钮(打开文件资源管理器窗口)时,如果用户按下取消,面板会将文件窗口绘制到面板上。我将如何解决这些问题?

public void paintComponent(Graphics g){
    super.paintComponents(g);
    g.fillOval(myX - radius, myY - radius, 2 * radius, 2 * radius);
    if(img != null)
        g.drawImage(img, 0, 0, null);
} 

下面的部分是 actionPerformed 方法的内部

if(source == clear){
    g.setBackground(Color.WHITE);
    g.clearRect(0, 0, getWidth(), getHeight());
    repaint();
}

缓冲图像和图形

BufferedImage img = new BufferedImage(1000, 1000, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = img.createGraphics();

【问题讨论】:

    标签: java swing jframe jpanel paint


    【解决方案1】:

    我怀疑Graphics 上下文g 在您的ActionListener 中无效,可能是由于不当使用getGraphics()。相反,让您的 ActionListener 更新视图类中的字段,并使用更新后的值修改 paintComponent() 中的 Graphics 上下文。

    在这个完整的example 中,buttonPanelactionPerformed() 的各种实现会更新DrawingArea 中的属性。 paintComponent()DrawingArea 中的实现然后知道每次 调用它时要绘制什么。

    【讨论】:

    • 我在顶部添加了缓冲图像和图形声明。
    • 很高兴你把它整理好了;看起来您将BufferedImage 的有效Graphics 上下文与提供给paintComponent() 的上下文混淆了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 1970-01-01
    • 2011-09-08
    • 2015-04-23
    • 1970-01-01
    相关资源
    最近更新 更多