javaswingjlabelactionevent

Smaller program to take click input of mouse from multiple JLabel


I have a bunch of labels in a single frame which basically serves as a multi-line output for displaying text. At certain points of the program the user needs select a option from a given choices. The way they do this is by clicking on the appropriate JLabel.

I tried with a JLabel array, but the functions do not work. I then made a separate ActionEvent for each JLabel, which works, but is there a elegant or efficient code for this?


Solution

  • youre welcome.

    you described your problem and i think i can follow.

    you could figure out the similarites the ActionListeners have and put those similarities into a super-Class

    for me, another possibility seems to be an 'all-in-one' ActionListener. its actionPerformed-Method has got a paramter of type ActionEvent. this ActionEvent provides a getSource()-Method, you can retrieve the JComponent the ActionEvent occured on. so if you give names to your JLabels, you can check for the name(s) in the actionPerformed-Method

    Edit

    like this way:

    public void actionPerformed(final ActionEvent actionEvent) {
        final String name = ((JComponent) actionEvent.getSource()).getName();
        switch (name) {
            case "label1":
                handleLabel1();
                break;
            case "label2":
                handleLabel2();
                break;
            case "label3":
                handleLabel3();
                break;
            default:
                break;
        }
    }
    

    Edit 1

    import java.awt.AWTEvent;
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.MouseEvent;
    import java.awt.event.MouseListener;
    
    import javax.swing.BoxLayout;
    import javax.swing.JButton;
    import javax.swing.JComponent;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.SwingUtilities;
    import javax.swing.WindowConstants;
    
    public class Application extends JFrame {
        private abstract class MyComponentListener implements MouseListener, ActionListener {
            protected void actionOnButton(final AWTEvent e) {
                final JButton button = (JButton) e.getSource();
                switch (button.getName()) {
                    case "button1":
                        System.out.println("Hello World");
                        break;
                    default:
                        System.out.println("mouse button one clicked on " + button.getName());
                        break;
                }
                // more general
                this.actionOnComponent(e);
            }
    
            protected void actionOnComponent(final AWTEvent e) {
                final JComponent component = (JComponent) e.getSource();
                final int index = Integer.valueOf(component.getName().replaceAll("[^0-9]", "")).intValue();
                switch (index) {
                    case 1:
                        System.out.println("Hello World");
                        break;
                    default:
                        System.out.println("mouse button one clicked on " + component.getName());
                        break;
                }
            }
    
            protected void actionOnLabel(final AWTEvent e) {
                final JLabel label = (JLabel) e.getSource();
                switch (label.getName()) {
                    case "label1":
                        System.out.println("Hello World");
                        break;
                    default:
                        System.out.println("mouse button one clicked on " + label.getName());
                        break;
                }
                // more general
                this.actionOnComponent(e);
            }
        }
    
        private class MyListener extends MyComponentListener {
            /**
             * {@link ActionListener#actionPerformed(ActionEvent)}
             */
            @Override
            public void actionPerformed(final ActionEvent e) {
                System.out.println("next line(s) generated by ActionListener");
                this.actionOnButton(e);
            }
    
            @Override
            public void mouseClicked(final MouseEvent e) {
                // whole process of mouse button down and up
                if ((e.getButton() == 1)) {
                    System.out.println("next line(s) generated by MouseListener");
                    if ((e.getSource() instanceof JLabel)) {
                        this.actionOnLabel(e);
                    } else if (e.getSource() instanceof JButton) {
                        this.actionOnButton(e);
                    }
                }
            }
    
            @Override
            public void mouseEntered(final MouseEvent e) {
                // on mouse over
            }
    
            @Override
            public void mouseExited(final MouseEvent e) {
                // on mouse out
            }
    
            @Override
            public void mousePressed(final MouseEvent e) {
                // mouse button down
            }
    
            @Override
            public void mouseReleased(final MouseEvent e) {
                // mouse button up after down
            }
        }
    
        private static final long serialVersionUID = 1L;
    
        private Application() {
            super();
        }
    
        public void start() {
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            this.getContentPane().setLayout(new BoxLayout(this.getContentPane(), BoxLayout.PAGE_AXIS));
            this.addLabel("Hello World - Label", "label1");
            this.addLabel("Label 2", "label2");
            this.addLabel("Label 3", "label3");
            this.addButton("Hello Word - Button", "button1");
            this.addButton("Button 2", "button2");
            final Dimension dimension = new Dimension(500, 150);
            this.setSize(dimension);
            this.setPreferredSize(dimension);
            this.setVisible(true);
        }
    
        private void addButton(final String text, final String name) {
            final JButton button = new JButton(text);
            button.setName(name);
            button.addMouseListener(new MyListener());
            button.addActionListener(new MyListener());
            this.getContentPane().add(button);
        }
    
        private void addLabel(final String text, final String name) {
            final JLabel label = new JLabel(text);
            label.setName(name);
            label.addMouseListener(new MyListener());
            this.getContentPane().add(label);
        }
    
        public static void main(final String[] args) {
            final Application app = new Application();
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    app.start();
                }
            });
        }
    }