-->

Is it possible to define your own 'controller&

2019-07-07 01:39发布

问题:

I would like to use Window Builder and use the MVC paradigm simultaneously. It is very messy with a complex window when Window Builder adds all the code to just one file.

I would like the default file created to be the 'view'.

I would like to keep my control actions (event listeners) in a 'controller' class. Is there a way to have Window builder automatically put the event listeners in a class of your choice rather than adding to one monolithic file?

回答1:

I don't know how Eclipse's Window Builder works, but I do know that NetBean's creates anonymous inner classes that call a custom method for each button and then allows the programmer to alter the body of the custom method. If Eclipse is similar, then you can simply have this custom method call a method of your Control object. Sure it adds a layer of indirection, but it's a small price to pay to give you complete control over your control.

For instance, if I create a JButton called "myButton" and then have the code generator create an action for my button, it will create this code:

    myButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            myButtonActionPerformed(evt);
        }
    });

and will allow me to access and write code in the generated method, myButtonActionPerformed:

private void myButtonActionPerformed(java.awt.event.ActionEvent evt) {
   // TODO add your handling code here:
}

And inside of this method I would call my Control's method:

private void myButtonActionPerformed(java.awt.event.ActionEvent evt) {
   if (myControl != null) {
      myControl.myButtonAction();
   }
}

The control class could look something like

class MyControl {

    void myButtonAction() {
        //TODO: implement control code
    }

}

The GUI would need a setControl(MyControl myControl) method in order to "inject" the control into the GUI.



回答2:

Another way of splitting up your code is to use the wizard to create JPanels as your own controls, then add those in a layout in the main window using the "Choose component" tool (looks like three beans) from the palette. Easy and much cleaner. Although I understand it still merges the "V" and "C" in MVC...