Click listener在BufferedImage和Icon

时间:2017-05-04 08:24:46

标签: java swing

我一直在寻找一个解决方案已经有一段时间了,但是我还没有找到一个解决方案,所以为什么不自己提问呢?这是一个更大的程序的一部分,它围绕与图像转换有关的所有内容构建。

我首先构建了这个,所以我可以稍后将它添加到更大的程序中。我得到的错误是当我想从显示的图像中选择一个特定的像素。因为JPanel上显示的Java图标不能应用.getRGB和.setRGB方法,所以我将图像转换为BufferedImage。但是,BufferedImage无法直接显示在JPanel上。这就是图标存在的原因。

现在唯一的问题是,每次点击图片时,我都会收到错误。

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: sun.awt.image.ToolkitImage cannot be cast to java.awt.image.BufferedImage
at ImageWindow.Window1$3.mouseClicked(Window1.java:158)
at java.awt.Component.processMouseEvent(Unknown Source)
at javax.swing.JComponent.processMouseEvent(Unknown Source)
at java.awt.Component.processEvent(Unknown Source)
at java.awt.Container.processEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Window.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$500(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.awt.EventQueue$4.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

以下是我用于此的代码:

import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;


import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Color;

import net.miginfocom.swing.MigLayout;
import javax.swing.JScrollPane;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.JTextField;
import javax.swing.JFileChooser;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JToolBar;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.awt.Dimension;
import javax.swing.JProgressBar;
import javax.swing.SwingConstants;
import java.awt.Canvas;

public class Window1 {

    File File1 = new File("");
    String pathName = "";
    int accepted;
    int x;
    int y;
    int colour;
    ImageIcon icon;
    int red;
    int green;
    int blue;
    int width;
    int height;
    BufferedImage image;
    int c1num;

    //BufferedImage image1 = new BufferedImage(null, null, false, null);

    private JFrame frame;
    private JTextField textField;
    private JTextField textField_1;
    private JTextField textField_2;
    private JTextField textField_3;
    private JTextField textField_4;
    private JTextField textField_5;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Window1 window = new Window1();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the parent application.
     */
    public Window1() {
        initialize(); //More other windows can be added to this later
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setBounds(100, 100, 450, 300);
        frame.getContentPane().setLayout(new MigLayout("debug", "[grow][grow]", "[][266.00,grow]"));

        JToolBar toolBar = new JToolBar();
        frame.getContentPane().add(toolBar, "flowx,cell 0 0 2 1,aligny top");

        JLabel lblImage = new JLabel("");
        lblImage.setHorizontalAlignment(SwingConstants.CENTER);





        lblImage.setVerticalAlignment(SwingConstants.TOP);

        JButton btnOpenImage = new JButton("Open Image");

        btnOpenImage.addActionListener(new ActionListener() { 
              public void actionPerformed(ActionEvent ec) { 
                JFileChooser openimage = new JFileChooser("Open image");
                FileNameExtensionFilter filter = new FileNameExtensionFilter("JPEG file", "jpg", "jpeg");
                openimage.setFileFilter(filter);
                accepted = openimage.showOpenDialog(null);
                File1 = openimage.getSelectedFile();
                try {
                    if (accepted == JFileChooser.APPROVE_OPTION) {
                        pathName = openimage.getSelectedFile().getPath();
                        icon = new ImageIcon(pathName);

                        lblImage.setIcon(icon);
                    } else {
                        JOptionPane.showMessageDialog(null, "Feel Free to Look Later");
                    }
                } catch (Exception ec1) {
                    // TODO Auto-generated catch block
                    ec1.printStackTrace();
                }
            }  
              } 
             );


        BufferedImage buffered = null;


        try {
         buffered = ImageIO.read(getClass().getResourceAsStream("images/test1.jpg"));
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


        Color c = new Color(buffered.getRGB(x,y));


        lblImage.addMouseListener(new MouseListener() {
            @Override
            public void mouseClicked(MouseEvent e) {
                x=e.getX();
                y=e.getY();


                Image image = icon.getImage();
                BufferedImage buffered = (BufferedImage) image;
                System.out.println(x+","+y);//these co-ords are relative to the component
                colour = buffered.getRGB(x,y);

                red = c.getRed();
                green = c.getGreen();
                blue = c.getBlue();
                //Integer.toBinaryString(i)
                System.out.println(red + " " + green + " " + blue);
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseExited(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mousePressed(MouseEvent e) {
                // TODO Auto-generated method stub

            }

            @Override
            public void mouseReleased(MouseEvent e) {
                // TODO Auto-generated method stub

            }
        });


        toolBar.add(btnOpenImage);

        JButton btnExit = new JButton("Exit");
        btnExit.addActionListener(new ActionListener() { //here, the functionality for the "exit" button is added.
            public void actionPerformed(ActionEvent ev) {
                System.exit(0);
                }
              });

        JButton btnSaveImage = new JButton("Save Image");
        btnSaveImage.addActionListener(new ActionListener() { //here, the functionality for the "exit" button is added.
            public void actionPerformed(ActionEvent ev) {
                File output = new File("image.jpg");
                try {
                    ImageIO.write(buffered, "jpg", output);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                }
              });
        toolBar.add(btnSaveImage);
        toolBar.add(btnExit);

        JScrollPane scrollPane = new JScrollPane();
        frame.getContentPane().add(scrollPane, "cell 0 1,grow");



        scrollPane.setViewportView(lblImage);

        JPanel panel_1 = new JPanel();
        frame.getContentPane().add(panel_1, "cell 1 1,width max(60, 10%),grow");

        Box verticalBox = Box.createVerticalBox();
        panel_1.add(verticalBox);

        Box horizontalBox = Box.createHorizontalBox();
        verticalBox.add(horizontalBox);

        Box verticalBox_2 = Box.createVerticalBox();
        horizontalBox.add(verticalBox_2);

        JLabel label = new JLabel("R1");
        verticalBox_2.add(label);

        Component verticalStrut_6 = Box.createVerticalStrut(8);
        verticalBox_2.add(verticalStrut_6);

        JLabel label_1 = new JLabel("R2");
        verticalBox_2.add(label_1);

        Component verticalStrut_7 = Box.createVerticalStrut(8);
        verticalBox_2.add(verticalStrut_7);

        JLabel label_2 = new JLabel("R3");
        verticalBox_2.add(label_2);

        Component verticalStrut_8 = Box.createVerticalStrut(20);
        verticalBox_2.add(verticalStrut_8);

        JLabel label_3 = new JLabel("R1.1");
        verticalBox_2.add(label_3);

        Component verticalStrut_9 = Box.createVerticalStrut(8);
        verticalBox_2.add(verticalStrut_9);

        JLabel label_4 = new JLabel("R2.1");
        verticalBox_2.add(label_4);

        Component verticalStrut_10 = Box.createVerticalStrut(8);
        verticalBox_2.add(verticalStrut_10);

        JLabel label_5 = new JLabel("R3.1");
        verticalBox_2.add(label_5);

        Box horizontalBox_1 = Box.createHorizontalBox();
        horizontalBox.add(horizontalBox_1);

        Box verticalBox_3 = Box.createVerticalBox();
        horizontalBox_1.add(verticalBox_3);

        String red1 = (red + "");
        textField = new JTextField();
        textField.setText("red");

        textField.setText(red1);

        textField.setColumns(10);
        verticalBox_3.add(textField);


        String green1 = (green + "");
        textField_1 = new JTextField();
        textField_1.setText("green");

        textField_1.setText(green1);

        textField_1.setColumns(10);
        verticalBox_3.add(textField_1);


        String blue1 = (blue + "");
        textField_2 = new JTextField();
        textField_2.setText("blue");

        textField_2.setText(blue1);

        textField_2.setColumns(10);
        verticalBox_3.add(textField_2);


        Component verticalStrut_11 = Box.createVerticalStrut(20);
        verticalBox_3.add(verticalStrut_11);

        textField_3 = new JTextField();
        textField_3.setText("Text1.1");
        textField_3.setColumns(10);
        verticalBox_3.add(textField_3);

        textField_4 = new JTextField();
        textField_4.setText("Text2.1");
        textField_4.setColumns(10);
        verticalBox_3.add(textField_4);

        textField_5 = new JTextField();
        textField_5.setText("Text3.1");
        textField_5.setColumns(10);
        verticalBox_3.add(textField_5);

        Component verticalStrut = Box.createVerticalStrut(20);
        verticalBox.add(verticalStrut);

        width = buffered.getWidth();
        height = buffered.getHeight();
        Color col1 = new Color(red, green, blue);
        c1num = col1.getRGB();

        JButton btnNewButton = new JButton("Save"); //The button on the panel to set the colourk into the image
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                buffered.setRGB(width,height, c1num);

            }
        });
        verticalBox.add(btnNewButton);
    }

}

1 个答案:

答案 0 :(得分:4)

我认为错误非常自我解释,Image中存储的ImageIcon实例不是BufferedImage的实例,相反,您需要绘制图标到BufferedImage

例如:

Icon icon = ...;
BufferedImage img = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
icon.paintIcon(null, g2d, 0, 0);
g2d.dispose();