【问题标题】:draw buffered image ontop of another buffered image在另一个缓冲图像之上绘制缓冲图像
【发布时间】:2012-06-09 13:11:36
【问题描述】:

我的目标是将一些缓冲图像绘制到另一个图像上。然后所有这些东西都会绘制到其他一些缓冲图像上,依此类推。最后把它画在一个面板上。 现在我正在尝试将缓冲图像绘制到面板上,但没有任何效果。我的缓冲图像看起来完全是白色的:

public class Main2 {
    public static void main(String[] args) {
        JFrame frame = new JFrame("asdf");
        final JPanel panel = (JPanel) frame.getContentPane();
        frame.setSize(500,500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        panel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                somepaint(panel);
            }
        });
    }

    private static void somepaint(JPanel panel) {
        BufferedImage image = new BufferedImage(200,200,BufferedImage.TYPE_INT_ARGB);
        image.getGraphics().setColor(Color.red);
        image.getGraphics().fillRect(0, 0, 200, 200);

        Graphics2D graphics = (Graphics2D) panel.getGraphics();
        graphics.setColor(Color.magenta);
        graphics.fillRect(0, 0, 500, 500);
        graphics.drawImage(image, null, 0, 0); // draws white square instead of red one
    }
}

谢谢

【问题讨论】:

  • “最后把它画在面板上。” 为什么不把它添加到ImageIcon,添加到JLabel,然后添加标签到面板?

标签: java swing bufferedimage graphics2d


【解决方案1】:

回复:

private static void somepaint(JPanel panel) {
    BufferedImage image = new BufferedImage(200,200,BufferedImage.TYPE_INT_ARGB);
    image.getGraphics().setColor(Color.red);
    image.getGraphics().fillRect(0, 0, 200, 200);

    Graphics2D graphics = (Graphics2D) panel.getGraphics();

这不是您在 JPanel 或 JComponent 内部绘制的方式。

不要在组件上调用getGraphics(),因为返回的 Graphics 对象将是短暂的,用它绘制的任何东西都不会持久。而是在其 paintComponent(Graphics G) 方法覆盖内进行 JPanel 的绘图。您需要创建一个扩展 JPanel 的类以覆盖 paintComponent(...)

最重要的是,看看如何正确地做 Swing 图形,不要猜测。你需要先阅读Swing Graphics Tutorials,因为它会要求你抛出一些不正确的假设(我知道这是我必须做的才能让它正确)。

【讨论】:

    【解决方案2】:

    您需要在drawImage() 调用中更正您的参数。改变这个:

    graphics.drawImage(image, null, 0, 0); 
    

    graphics.drawImage(image, 0, 0,null);
    

    查看Java docs了解更多详情。

    【讨论】:

      猜你喜欢
      • 2018-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-25
      相关资源
      最近更新 更多