简体   繁体   中英

Can I return something from mouseClicked to my main

We are supposed to display an image and a button. If you press the button the image should change. My problem is that im unsure how to return the changed image. Since i cant change the return type from mouseClicked. I also tried get and set but this doesnt work because im working on diffrent objects since mouseClicked and main are in diffrent classes. This is what i have so far:

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

class AppFrame extends JFrame {
    public AppFrame(String title) {
        super(title);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

class Original extends MouseAdapter {
    public void mouseClicked(MouseEvent e) {
        if (e.getClickCount() > 0){
            try {
                AppDrawEvent obj = new AppDrawEvent();
                BufferedImage img = obj.getImg();
                int w = img.getWidth();
                int h = img.getHeight();
                for (int i = 0; i < h; i++) {
                    for (int j = 0; j < w; j++) {
                        int pixel = img.getRGB(j, i);
                        img.setRGB(j,i,pixel+100);
                    }
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}

public class AppDrawEvent
{
    private BufferedImage img=ImageIO.read(new File("FILEPATH"));
    public AppDrawEvent() throws IOException {
    }

    public BufferedImage getImg() {
        return img;
    }

    public void setImg(BufferedImage img) {
        this.img = img;
    }

    public static void main(String[] args ) throws IOException
    {
        JFrame frame = new AppFrame("TITEL");
        JPanel panel = new JPanel();
        frame.add(panel);

        FlowLayout Layout = new FlowLayout(FlowLayout.LEFT);
        panel.setLayout(Layout);

        JButton bOrg = new JButton("Original");
        panel.add(bOrg, BorderLayout.NORTH);
        Original m = new Original();
        bOrg.addMouseListener(m);

        AppDrawEvent obj = new AppDrawEvent();
        BufferedImage img= obj.getImg();
        JLabel picLabel = new JLabel(new ImageIcon(img));
        panel.add(picLabel, BorderLayout.CENTER);

        frame.setSize(new Dimension(img.getWidth()+150,img.getHeight()+100));
        frame.setVisible(true);
       // frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM