JPanel Image获取多次运行

时间:2012-11-13 15:49:13

标签: java swing jpanel bufferedimage paintcomponent

我想让这两段代码一起工作,但我遇到了问题。第一部分代码构建了由我的编辑器(Netbeans GUI Builder for Java)生成的表单,不确定这是否是导致问题的原因。

当我运行项目时,我的代码(第二个代码块)运行并反转图像的颜色(确切地说它应该做什么),然后它恢复到原始图像(非 - 不应该发生,图像应该在面板中显示为非反转图像。然后,当我单击框架边框重新调整大小时,面板图像闪烁为反转,然后非反转,然后反转。再次点击它会做同样的事情,但在非倒置时停止。造成这个奇怪问题的原因是什么?

package weblaftest;

/**
 *
 * @author Ryan
 */
public class Main extends javax.swing.JFrame{
    /**
     * Creates new form Main
     */
    public Main(){
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jInternalFrame1 = new javax.swing.JInternalFrame();
        test1 = new weblaftest.test();

        jInternalFrame1.setVisible(true);

        javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane());
        jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout);
        jInternalFrame1Layout.setHorizontalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );
        jInternalFrame1Layout.setVerticalGroup(
            jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        javax.swing.GroupLayout test1Layout = new javax.swing.GroupLayout(test1);
        test1.setLayout(test1Layout);
        test1Layout.setHorizontalGroup(
            test1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 409, Short.MAX_VALUE)
        );
        test1Layout.setVerticalGroup(
            test1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 362, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(test1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(262, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(83, Short.MAX_VALUE)
                .addComponent(test1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(74, 74, 74))
        );

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

    /**
     * @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(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }catch(InstantiationException ex){
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }catch(IllegalAccessException ex){
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }catch(javax.swing.UnsupportedLookAndFeelException ex){
            java.util.logging.Logger.getLogger(Main.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

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

    // Variables declaration - do not modify
    private javax.swing.JInternalFrame jInternalFrame1;
    private weblaftest.test test1;
    // End of variables declaration
}

这部分就是我写的,它是显示图像的面板代码,出于测试目的,所有它都反转了面板中显示的图像上的颜色。

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package weblaftest;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import weblaftest.grapics.Colors;

/**
 *
 * @author Ryan
 */
public class test extends javax.swing.JPanel{
private BufferedImage image;
    /**
     * Creates new form test
     */
    public test(){
        try{
            image = ImageIO.read(new File("/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg"));
        }catch(IOException e){
        }
    }

    @Override
    public void paintComponent(Graphics g){
        super.paintComponent(g);
        int width = image.getWidth();
        int height = image.getHeight();
        for(int x = 0; x < width; x++){
            for(int y = 0; y < height; y++){
                int color = image.getRGB(x, y);
                int red = Colors.red(color);
                int green = Colors.green(color);
                int blue = Colors.blue(color);

                int rgb = Colors.rgba(255 - red, 255 - green, 255 - blue);
                image.setRGB(x, y, rgb);
            }
        }
        g.drawImage(image, 0, 0, width, height, Color.black, null);
    }


    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );
    }// </editor-fold>
    // Variables declaration - do not modify
    // End of variables declaration
}

这是请求的Colors类:

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package weblaftest.grapics;

/**
 *
 * @author Ryan
 */
public class Colors{

    public static int rgba(int red, int green, int blue, Integer alpha){
        int rgba = alpha;
        rgba = (rgba << 8) + red;
        rgba = (rgba << 8) + green;
        rgba = (rgba << 8) + blue;
        return rgba;
    }
    public static int rgba(int red, int green, int blue){
        int rgba = 255;
        rgba = (rgba << 8) + red;
        rgba = (rgba << 8) + green;
        rgba = (rgba << 8) + blue;
        return rgba;
    }

    public static int alpha(int color){
        return color >> 24 & 0x0FF;
    }

    public static int red(int color){
        return color >> 16 & 0x0FF;
    }

    public static int green(int color){
        return color >> 8 & 0x0FF;
    }

    public static int blue(int color){
        return color & 0x0FF;
    }
}

1 个答案:

答案 0 :(得分:1)

  • 仅保留paintComponent()用于绘制,不应在paintComponent(..)
  • 中进行长时间的处理
  • 班级名称应以大写字母开头,即Test

问题在于:

@Override
public void paintComponent(Graphics g){
    super.paintComponent(g);
    int width = image.getWidth();
    int height = image.getHeight();
    for(int x = 0; x < width; x++){
        for(int y = 0; y < height; y++){
            int color = image.getRGB(x, y);
            int red = Colors.red(color);
            int green = Colors.green(color);
            int blue = Colors.blue(color);

            int rgb = Colors.rgba(255 - red, 255 - green, 255 - blue);
            image.setRGB(x, y, rgb);
        }
    }
    g.drawImage(image, 0, 0, width, height, Color.black, null);
}

在第一次调用BufferedImage时,在连续调用时绘制反转paintComponent(),它将重新转换并每次反转。

反过来反转构造函数中的BufferedImage并仅绘制BufferedImage中的倒置paintComponent(..)不要在paintComponent(..)中反转,因此在反转和原始图像之间切换为{ {1}}重新调整大小:

JFrame