在另一个缓冲图像之上绘制缓冲图像

3

我的目标是将一些缓冲图像绘制到另一个图像上,然后将所有这些内容绘制到另一个缓冲图像上,最后将这个图像绘制在面板的顶部。 目前我正在尝试将缓冲图像绘制到面板上,但什么都不起作用。我的缓冲图像看起来完全是白色的:

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”,然后将标签添加到面板中呢? - Andrew Thompson
2个回答

6

回复:

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对象生命短暂,使用它绘制的任何内容都不会持久化。相反,应该在JPanel的paintComponent(Graphics G)方法覆盖内进行绘制。您需要创建一个扩展JPanel类以覆盖paintComponent(...)

最重要的是,要正确了解如何进行Swing图形处理,请不要猜测。您需要先阅读Swing Graphics Tutorials,这将要求您放弃一些不正确的假设(我知道我必须这样做才能搞定它)。


3
您需要在drawImage()函数中更正参数。将其修改为以下内容:
graphics.drawImage(image, null, 0, 0); 

to

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

查看Java文档以获取更多细节。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接