Standards for using inner classes for GUI?

I'm curious about standard practice with inner classes (in Java, but I suppose this applies to all OO languages). So I have a subclass of JFrame ControllerWindowthat contains a subclass of JPanel MapPanelthat I draw on (so it needs to overwrite the paintComponent method) and which the mouse listener should implement. My current solution that works is to have MapPanelin a separate class that implements MouseListener, but when I showed this to the guy who is leading my course, the other day he seemed to think (we have a little language barrier), it should be to an inner class in ControllerWindowor at least a MouseListener should be an inner class.

So my question is what would be the standard solution here, put MouseListener in an inner class, JPanel in another inner class, or still in its own separate class? Does JPanel implement MouseListener in one inner class? And why?

The most important thing for me is that it works, but I would like to learn and understand the standard practices behind these things, if possible.

EDIT: A very simplified version of the current code below.

class ControllerWindow extends JFrame{
    ...
    MapPanel drawPanel = new MapPanel();
    ...
}

and a separate class:

class MapPanel extends JPanel implements MouseListener{

    ...

    public void paintComponent(Graphics g){
        ...//fillRects etc.
    }

    //MouseListener methods
    public void mouseReleased(MouseEvent e){
        requestFocus();
        ...
        repaint()
        ...
    }
    public void mousePressed(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseClicked(MouseEvent e){}
}

There may also be a situation where it would be acceptable to put both classes in the same file? I do not intend to use it MapPanelfor anything else ControllerWindow.

+5
source share
5 answers

, , ( , GUI = ), . , . , , / , , .

, MapPanel ControllerWindow, MapPanel, ControllerWindow, MapPanel .

MouseListener MapPanel, ( , MapPanel "", "", ). ControllerWindow, "" MapPanel. ( , : MapPanel , , , , ControllerWindow. , , ControllerWindow).

, MapPanel MouseListener, MapPanel ( ), , , .

+4

, ( ), "" , , , , , .

EDIT: , . , , MouseListener, , , .

+7

, .

button1.click( function(event){ do something x...  } );
button2.click( function(event){ do something y...  } );
radio2.check ( function(event){ do something z... } );

java 7 - . , . , .

+1

- . , , , . .

0
source

I found this article helpful: http://www.retrologic.com/innerclasses.doc3.html

In general, when you need to use a method pointer; extend adapter classes as inner classes to simplify code.

0
source

All Articles