javaswingjtextareamouselistenermouse-listeners

Single MouseListener Event to get text from JTextArea


I am creating a football draw app. I currently have 9 text areas which hold 6 different teams. I have attached a MouseListener to each text area. When you click on the text area, you see a new window with each team seperated into a group format.

I have an issue trying to get the text from the text areas. I could achieve this by adding a MouseListener to each individual text area but this violates the Don't Repeat Yourself (DRY) principle as far as I am aware.

I have included my code below:

gui.getTable1().addMouseListener(new tableListener());
gui.getTable2().addMouseListener(new tableListener());
gui.getTable3().addMouseListener(new tableListener());
gui.getTable4().addMouseListener(new tableListener());
gui.getTable5().addMouseListener(new tableListener());
gui.getTable6().addMouseListener(new tableListener());
gui.getTable7().addMouseListener(new tableListener());
gui.getTable8().addMouseListener(new tableListener());
gui.getTable9().addMouseListener(new tableListener());


public static class TableListener implements MouseListener {

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

    @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
        //get text from text area and pass to new GUI
    }

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

I would like to use the TableListener private class for all my text areas instead of 9 different MouseListeners. I think this can be done in a single line but I can't think how. Can someone please help?


Solution

  • Attach just one instace of listener to all the textareas and use e.getSource() to get event source textarea.