Home > Enterprise >  How to set the focus to an image or a label ?[Java Swing]
How to set the focus to an image or a label ?[Java Swing]

Time:04-13

Let's say I have several images, each of them in a label, is there a way to set the focus on one of the images or JLabels by clicking at it and do some image processing on the clicked image (blur, black and white...).

Any help is appreciated

CodePudding user response:

You could...

Use JButtons instead, it's kind of what they are designed for...

enter image description here

import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JFrame frame = new JFrame();
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() throws IOException {
            setLayout(new GridLayout(-1, 3));
            for (int index = 1; index < 13; index  ) {
                BufferedImage image = ImageIO.read(getClass().getResource("/images/Cute"   index   ".png"));
                Image scaled = image.getScaledInstance(50, -1, Image.SCALE_SMOOTH);
                JButton btn = new JButton(new ImageIcon(scaled));
                btn.putClientProperty("image", image);
                add(btn);
                btn.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        JButton btn = (JButton) e.getSource();
                        BufferedImage img = (BufferedImage) btn.getClientProperty("image");
                        // Do stuff
                    }
                });
            }
        }

    }
}

See enter image description here

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    JFrame frame = new JFrame();
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() throws IOException {
            setLayout(new BorderLayout());
            DefaultListModel<BufferedImage> model = new DefaultListModel<>();
            for (int index = 1; index < 13; index  ) {
                BufferedImage image = ImageIO.read(getClass().getResource("/images/Cute"   index   ".png"));
                model.addElement(image);
            }

            JList list = new JList(model);
            list.setCellRenderer(new BufferedImageListRenderer());
            list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
            list.setVisibleRowCount(4);

            list.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    BufferedImage image = (BufferedImage)list.getSelectedValue();
                    // Do stuff
                }
            });
            list.setSelectedIndex(0);

            add(new JScrollPane(list));
        }

        protected class BufferedImageListRenderer extends DefaultListCellRenderer {
            @Override
            public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                if (value instanceof BufferedImage) {
                    setText(null);
                    // This is expensive, I'd normally have it cached somewhere
                    Image scaled = ((BufferedImage)value).getScaledInstance(50, -1, Image.SCALE_SMOOTH);
                    setIcon(new ImageIcon(scaled));
                }
                return this;
            }
        }

    }
}

See enter image description here

Here is a runnable code:

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class Main {
    JFrame frame;
    JLabel labelWithFocus;
    
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    frame = new JFrame();
                    frame.setAlwaysOnTop(true);
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

    public JLabel getLabelWithFocus() {
        return labelWithFocus;
    }

    
    public class TestPane extends JPanel {

        private static final long serialVersionUID = 40666L;

        public TestPane() throws IOException {
            GridLayout layout = new GridLayout(-1, 3);
            layout.setHgap(40);
            layout.setVgap(15);
            setLayout(layout);
            setBackground(Color.WHITE);
            for (int index = 1; index < 13; index  ) {
                BufferedImage image = ImageIO.read(getClass().getResource("/images/Cute"   index   ".png"));
                Image scaled = image.getScaledInstance(50, -1, Image.SCALE_SMOOTH);
                JLabel lbl = new JLabel(new ImageIcon(scaled));
                lbl.setName("Cute"   index   ".png");
                lbl.putClientProperty("image", image);
                add(lbl);
                lbl.addMouseListener(new MouseAdapter() {
                    @Override
                    public void mouseClicked(MouseEvent e) {
                        if (labelWithFocus != null) {
                            labelWithFocus.setBorder(null);
                        }
                        labelWithFocus = (JLabel) e.getSource();
                        BufferedImage img = (BufferedImage) labelWithFocus.getClientProperty("image");
                        lbl.setBorder(BorderFactory.createLineBorder(Color.RED, 2));
                        frame.setTitle(labelWithFocus.getName());
                        
                        // Do anything else you want...
                    }
                    
                    @Override
                    public void mouseEntered(MouseEvent e) {
                        JLabel lbl = (JLabel) e.getSource();
                        lbl.setBorder(BorderFactory.createLineBorder(Color.decode("#2eb8b8"), 1));
                    }
                    
                    @Override
                    public void mouseExited(MouseEvent e) {
                        JLabel lbl = (JLabel) e.getSource();
                         if (lbl == labelWithFocus) {
                            lbl.setBorder(BorderFactory.createLineBorder(Color.RED, 2));
                        }
                        else {
                            lbl.setBorder(null);
                        }
                    }
                });
            }
        }
    }
}
  • Related