Java Canvas绘制图像闪烁

标签 java swing awt

我总是在 StackOverflow 中寻找问题,但我似乎找不到这个问题的答案。

我正在使用 Java 创建带有 Swing 表单的应用程序。我已将 Canvas AWT 组件添加到 JFrame。

我从数据库预加载图像,将其绘制到 Canvas 中,然后将 JFrame 设置为可见。

问题是图像会闪烁:它显示几毫秒,然后重新绘制 JFrame。

为什么会发生这种情况?我也尝试重写 JFrame 中的 paint() 方法,并在每次调用 paint 时绘制图像。但事实并非如此。

按钮框架(主框架)-(将final String imgPath替换为您选择的示例图像)

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ButtonFrame extends javax.swing.JFrame {

    public ButtonFrame() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jButton1.setText("View Image");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(59, 59, 59)
                .addComponent(jButton1)
                .addContainerGap(44, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(54, 54, 54)
                .addComponent(jButton1)
                .addContainerGap(70, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        final String imgPath = "/tmp/img.png";

        try
        {
            BufferedImage bi = ImageIO.read(new File(imgPath));

            ImgFrame imgFrame = new ImgFrame();
            imgFrame.setImage(bi);
            imgFrame.setVisible(true);

//            imgFrame.setImageInCanvas(bi);

        } catch (IOException x) {}
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ButtonFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ButtonFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ButtonFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ButtonFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new ButtonFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    // End of variables declaration                   
}

ImageFrame(显示图像的框架)

import java.awt.Graphics;
import java.awt.image.BufferedImage;

public class ImgFrame extends javax.swing.JFrame {

    BufferedImage bi;

    public ImgFrame() {
        initComponents();
    }

    public void setImage(BufferedImage bi)
    {
        this.bi = bi;
    }

    public void setImageInCanvas(BufferedImage bi)
    {
        canvas1.getGraphics().drawImage(bi, 0, 0, null);
    }

    @Override
    public void paint(Graphics g)
    {
        setImageInCanvas(bi);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        canvas1 = new java.awt.Canvas();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, 266, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(canvas1, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

        pack();
    }// </editor-fold>                        


    // Variables declaration - do not modify                     
    private java.awt.Canvas canvas1;
    // End of variables declaration                   
}

视频示例: https://drive.google.com/file/d/0B53gOV_BD8J8Mm10LW5CN2E3M2M/view

<小时/>

问题已解决:

我已经重写了 JFrame 中的 paint 方法,如下所示:

@Override
public void paint(Graphics g)
{
    g.drawImage(bi, 0, 0, null);
}

其中 bi 是 BufferedImage。

然后,Canvas 与 Form 重叠,因为它被设置为适合 JFrame,并且图像未显示。我已将其删除(AWT Canvas ),图像现在显示在背景中。

非常感谢!

特别感谢 Dodd10x 和 Andrew Thompson。

最佳答案

不要混合使用 Swing 和 AWT。如果您在 JFrame 中显示,首先要更改的是从 Canvas 切换到 JComponent。

关于Java Canvas绘制图像闪烁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33086903/

相关文章:

java - 使用 Java 构建工具

java - 是否可以使用 for 循环来创建单选按钮?

java - Swing 问题绘制 2 个图像

java - java.awt.image.BufferedImage 的二值化规则是什么

java - 在 Swing 应用程序中扩展系统外观

java - 滚动 java 2d 游戏图 block map ,同时生成附加图 block

Java - 如何在定义的类中加载方法?

java - 在 App Engine 上定期运行一些 java?

java - TICTACTOE 游戏中的 while 循环无法正确执行

java - 粘贴菜单项,附加到 JTextField 时不执行任何操作