从控制器更改ComboBox值

时间:2014-06-03 15:17:35

标签: java swing model-view-controller map jcombobox

我正在使用模型 - 视图 - 控制器用于GUI,在视图中我已经定义了一个没有值的ComboBox。我想知道如何在视图中设置comboBox的项目,从Controller?

public class PlannerController {

    // the model that is being controlled
    private PlannerModel model;
    // the view that is being controlled
    private PlannerView view;

    //variables
    private Map<Route, List<Service>> timetable;

    /**
     * Initialises the Controller for the Journey Planner.
     */
    public PlannerController(PlannerModel model, PlannerView view) {
        this.model = model;
        this.view = view;


    }   

    class JourneySearchListener implements ActionListener {

        @Override
        public void actionPerformed(ActionEvent arg0) {
            // TODO Auto-generated method stub
            try {
                timetable = TimetableReader.read("timetable.txt");
            } catch (IOException | FormatException e) {
                e.printStackTrace();
            }

            //Set the comboBox Values
            Set<Route> comboBoxRoutes = timetable.keySet();
            Object[] comboArray = comboBoxRoutes.toArray();
            /* This is where I want to add the code*/
        }

下一堂课

public class PlannerView extends JFrame {

    // the model of the Journey Planner
    private PlannerModel model;
    private JComboBox startStation;
    private JComboBox endStation;

    // REMOVE THIS LINE AND DECLARE ANY ADDITIONAL VARIABLES YOU REQUIRE HERE

    /**
     * Creates a new Journey Planner window.
     */
    public PlannerView(PlannerModel model) {

        //set the default for the model
        this.model = model;
        //Make a way to close the program
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        //Create new container
        Container c = getContentPane();

        //create new frame      
        JFrame thePlanner = new JFrame("Journey Planner");


        //Add elements to interface
        addButtons(c);

    }

/* Helper Methods*/


    private void addButtons(Container c) {
        JPanel p = new JPanel();
        startStation = new JComboBox();
        endStation = new JComboBox();

        p.add(startStation);
        p.add(endStation);
        c.add(p,"North");
    }

1 个答案:

答案 0 :(得分:1)

Swing本身使用MVC-Pattern。 JComboBox在模型中有项目,您可以通过comboBox.setModel(model)设置它。为两个组合框提供getter,以便控制器能够调用view.getStartStation().setModel(model),其中model是您的PlannerModel,其扩展为DefaultComboBoxModel