简体   繁体   中英

Add JLabel to MouseListener

1st time poster here!

I am working on a Java Photo Viewer Gallery . I want to add all Labels from an ArrayList to a MouseListener . So I can go and open the picture the user clicked at in a new big window.

I have a file chooser where the user can select i number of pictures. I scaled them and put them in a:

ArrayList scaled = new ArrayList();

Error: The method addMouseListener(MouseListener) in the type Component is not applicable for the arguments (new ActionListener(){})

I tried to use

for (int i=0; i< scaled.size(); i++){
                        panel.add(new JLabel(new ImageIcon (scaled.get(i))));   
                        JLabel l = new JLabel(new ImageIcon(scaled.get(i)));
                        l.addMouseListener(this); //<- Compiler Error

                        }

The complete Code is:

import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Label;
import java.awt.List;
import java.awt.event.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.*;




public class ImageViewer {

    public static void main(String[] args) {

        JFrame frame = new ImageViewerFrame();
        frame.setTitle("PhotoViewer");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

}



@SuppressWarnings("serial")
class ImageViewerFrame extends JFrame implements MouseListener{
    JLabel label;
    JFileChooser chooser;
    JMenuBar menubar;
    JMenu menu;
    JMenuItem menuitem;

    JPanel panel = new JPanel();
//  JLabel l1= new JLabel("First");
//  JLabel l2= new JLabel("Second");
//  JLabel l3= new JLabel("Third");
//  JLabel l4= new JLabel("Fourth");




    public ArrayList<File> images = new ArrayList <File>();

    public ImageViewerFrame() {
        setSize(500,500);

        panel.setLayout(new GridLayout(0,5));

        label = new JLabel();
        add(label);
        add(panel);
        JButton test = new JButton ("TEST");
        test.addMouseListener(this);
        panel.add(test);
        panel.setVisible(true);
        chooser = new JFileChooser();
        chooser.setCurrentDirectory(new File("."));
        chooser.setMultiSelectionEnabled(true);
        menubar = new JMenuBar();
        setJMenuBar(menubar);

        menu = new JMenu("File");
        menubar.add(menu);

        menuitem = new JMenuItem("Open");
        menu.add(menuitem);
        ArrayList<ImageIcon> AL = new ArrayList<ImageIcon>();

        ArrayList<Image> scaled = new ArrayList<Image>();




        menuitem.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent event){

                        int result = chooser.showOpenDialog(null);

                        if(result == JFileChooser.APPROVE_OPTION) {

                            //label.setIcon(new ImageIcon(name));

                            File[] f = chooser.getSelectedFiles();

                            for(int i=0; i< f.length; i++)
                            {
                               images.add(f[i]);
                                ImageIcon imageicon = new ImageIcon(f[i].toString());
                                AL.add(imageicon);

                            }       

                            for (ImageIcon x : AL){
                                System.out.println(x);
                                Image image = x.getImage();
                                Image newimg = image.getScaledInstance(120,120, java.awt.Image.SCALE_SMOOTH);
                                scaled.add(newimg);
                            } 


                            for (int i=0; i< scaled.size(); i++){
                                panel.add(new JLabel(new ImageIcon (scaled.get(i))));   
                                JLabel l = new JLabel(new ImageIcon(scaled.get(i)));
                                l.addMouseListener(this);


                            }




                                                                }
                                    }
                            });




    }






    @Override
    public void mouseClicked(MouseEvent arg0) {


    }







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

    }







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

    }







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

    }







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

    }

}

It wont let me add the JLabel l to the MouseListener

First of all you don't add a label to a MouseListener. You add a MouseListener to the label. You didn't implement the MouseListener interface so you get the compile error. You need to implement all the methods (mousePressed, mouseReleased ...).

Read the section from the Swing tutorial on How to Write a MouseListener for working examples.

Also, once you get the MouseListener working you don't need to create two labels. The basic code might be something like:

JLabel l = new JLabel(new ImageIcon(scaled.get(i)));
label.addMouseListener(this); //<- Compiler Error
panel.add( label );

Finally, you may want to consider using a JList to display the Icons. It is more efficient because it just renders the images. Then you can use a ListSelectionListener to do processing when an image is selected. Read the section from the Swing tutorial on How to Use Lists for more information.

I would use an array to store all the mouse information. Example :

public class MyApp extends JFrame implements MouseListener, MouseWheelListener {

    public int[] mouse=new int[5];

    public void mousePressed(MouseEvent m) {
         if (m.getButton() == m.BUTTON1) {
             mouse[2]=1;
         }
         if (m.getButton() == m.BUTTON2) {
             mouse[3]=1;
         }
         if (m.getButton() == m.BUTTON3) {
             mouse[4]=1;
         }
    }
    public void mouseClicked(MouseEvent m) {
         if (m.getButton() == m.BUTTON1) {
             mouse[2]=3;
         }
         if (m.getButton() == m.BUTTON2) {
             mouse[3]=3;
         }
         if (m.getButton() == m.BUTTON3) {
             mouse[4]=3;
         }
    }
    public void mouseReleased(MouseEvent m) {
         if (m.getButton() == m.BUTTON1) {
             mouse[2]=2;
         }
         if (m.getButton() == m.BUTTON2) {
             mouse[3]=2;
         }
         if (m.getButton() == m.BUTTON3) {
             mouse[4]=2;
         }
    }
    public void mouseEntered(MouseEvent m) {
    }
    public void mouseExited(MouseEvent m) {
    }
    public void mouseWheelMoved(MouseWheelEvent w) {
         mouse[3]=w.getWheelRotation();
    }
    public MyApp() {
         super("MyApp");
         //Do your stuff here...
         //...
         //...
         setTitle("Image Picker");
         requestFocus();
         addMouseListener(this);
         addMouseWheelListener(this);
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setSize(1400,1000);
         setResizable(true);
         setVisible(true);
         int gc=0;
         Rectangle r;
         while (true){
             try {
             Thread.sleep(33);
             } catch(InterruptedException bug) {
             Thread.currentThread().interrupt();
             System.out.println(bug);
             }
             r=getComponents()[0].getBounds();
             gc=gc+1;
             if (gc==500) {
                 System.gc();
                 gc=0;
             }
             mouse[0]=MouseInfo.getPointerInfo().getLocation().x-getComponents()[0].getLocationOnScreen().x;
             mouse[1]=MouseInfo.getPointerInfo().getLocation().y-getComponents()[0].getLocationOnScreen().y;
             //Display labels
        }
    }

    public static void main(String args[]){
        new MyApp();
    }
}

The mouse array will be :

mouse[0] - mouse x pos
mouse[1] - mouse y pos
mouse[2] - left mouse button
mouse[3] - middle mouse button
mouse[4] - right mouse button
mouse[5] - mouse wheel rotation, 0 if none, else -n to n

And it should be easy to check if a point (the mouse) is over a rectangle (the label). If you dont know how to get the positions of the labels, simply use this code :

Rectangle r=getComponents()[1+n].getBounds();
//r.x, r.y, r.width, r.height

Hope it helps you !

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