Passing JMenuItem to Controller Class

2019-02-28 08:10发布

问题:

I Have 3 sets of JMenuItem on a View class of the MVC framework. I want to refer to them in the controll class EventController. Can someone show me this is achieved? Below is the event Controller. Class EventView consists of JMenuItem addEvent, editEvent, deleteEvent, how do I do the listeners for them in the Controller class. Can someone demonstrate using a sample code on top of my Controller class?

public class EventController implements ActionLister {
private EventModel model;
private EventView view;
private ActionListener actionListener;


public EventController(EventModel model, EventView view){
    this.model = model;
    this.view = view;
}

Second question, I can only update a JTable from the View class itself, so

public void updateEventTable() {
    try {
        String sql = "SELECT date as 'Date',eventName as 'Name', time as 'Time' FROM Event";
         pst = conn.prepareStatement(sql); 
         rs = pst.executeQuery();
         tableEvent.setModel(DbUtils.resultSetToTableModel(rs));
         tableEvent.getColumnModel().getColumn(0).setPreferredWidth(80);
         tableEvent.getColumnModel().getColumn(1).setPreferredWidth(170);
         tableEvent.getColumnModel().getColumn(2).setPreferredWidth(110);  
    }
    catch (Exception e ) {
        JOptionPane.showMessageDialog(null, e);
    } finally {
        try {
            rs.close(); pst.close();conn.close();;
        } catch(SQLException e){}
    }
}

This is bad practice having codes in View Class, Should ideally be in Model, but how to do this can you show me. The concepts is new to me and want to learn. Because of JTable I find it very difficult

回答1:

Let your model export instances of Action that can be added to menus and buttons as needed. Because database access is inherently asynchronous, let each such action use a worker thread to query the database in the background while updating the table mode on the EDT. See also A Swing Architecture Overview concerning the relationship between Swing components and models.

Addendum: Can you show me a code sample?

  • FileMenu is a very basic example of using Action to encapsulate functionality.

  • The example cited here uses Action more extensively in a JToolBar.

  • JHotDraw, cited here, is a very complex example that changes the available Action instances based on context, as discussed here.

  • This example offers a general examination of MVC in Swing.