当前位置: 首页 > 面试题库 >

Java Swing中的控制器是什么?

贺雪松
2023-03-14
问题内容

我想以有意义的方式使用Swing将MVC设计应用于Java应用程序。因此,我的问题是,如何在Java Swing中构造控制器?

我有两个选择:

  1. 每个组件侦听器都是自己的类,作为控制器包的一部分
  2. 每个组件侦听器都是视图包中的一个匿名类,该类将其调用委托给具有控制器方法的类。

两者都有可能吗?是偏好问题还是明确定义的?


问题答案:

Controller构成了组件接口的另一半,主要是交互的一半。控制器负责鼠标和键盘事件。

在Swing JButton等组件中是控制器。所有侦听器类都将事件重定向到具有您的业务逻辑的模型

例如:

主程序

import javax.swing.*;

public class CalcMVC {
    //... Create model, view, and controller.  They are
    //    created once here and passed to the parts that
    //    need them so there is only one copy of each.
    public static void main(String[] args) {

        CalcModel      model      = new CalcModel();
        CalcView       view       = new CalcView(model);
        CalcController controller = new CalcController(model, view);

        view.setVisible(true);
    }
}

视图

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;

class CalcView extends JFrame {
    //... Constants
    private static final String INITIAL_VALUE = "1";

    //... Components
    private JTextField m_userInputTf = new JTextField(5);
    private JTextField m_totalTf     = new JTextField(20);
    private JButton    m_multiplyBtn = new JButton("Multiply");
    private JButton    m_clearBtn    = new JButton("Clear");

    private CalcModel m_model;

    //======================================================= constructor
    /** Constructor */
    CalcView(CalcModel model) {
        //... Set up the logic
        m_model = model;
        m_model.setValue(INITIAL_VALUE);

        //... Initialize components
        m_totalTf.setText(m_model.getValue());
        m_totalTf.setEditable(false);

        //... Layout the components.      
        JPanel content = new JPanel();
        content.setLayout(new FlowLayout());
        content.add(new JLabel("Input"));
        content.add(m_userInputTf);
        content.add(m_multiplyBtn);
        content.add(new JLabel("Total"));
        content.add(m_totalTf);
        content.add(m_clearBtn);

        //... finalize layout
        this.setContentPane(content);
        this.pack();

        this.setTitle("Simple Calc - MVC");
        // The window closing event should probably be passed to the 
        // Controller in a real program, but this is a short example.
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    void reset() {
        m_totalTf.setText(INITIAL_VALUE);
    }

    String getUserInput() {
        return m_userInputTf.getText();
    }

    void setTotal(String newTotal) {
        m_totalTf.setText(newTotal);
    }

    void showError(String errMessage) {
        JOptionPane.showMessageDialog(this, errMessage);
    }

    void addMultiplyListener(ActionListener mal) {
        m_multiplyBtn.addActionListener(mal);
    }

    void addClearListener(ActionListener cal) {
        m_clearBtn.addActionListener(cal);
    }
}

控制者

import java.awt.event.*;

public class CalcController {
    //... The Controller needs to interact with both the Model and View.
    private CalcModel m_model;
    private CalcView  m_view;

    //========================================================== constructor
    /** Constructor */
    CalcController(CalcModel model, CalcView view) {
        m_model = model;
        m_view  = view;

        //... Add listeners to the view.
        view.addMultiplyListener(new MultiplyListener());
        view.addClearListener(new ClearListener());
    }


    ////////////////////////////////////////// inner class MultiplyListener
    /** When a mulitplication is requested.
     *  1. Get the user input number from the View.
     *  2. Call the model to mulitply by this number.
     *  3. Get the result from the Model.
     *  4. Tell the View to display the result.
     * If there was an error, tell the View to display it.
     */
    class MultiplyListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            String userInput = "";
            try {
                userInput = m_view.getUserInput();
                m_model.multiplyBy(userInput);
                m_view.setTotal(m_model.getValue());

            } catch (NumberFormatException nfex) {
                m_view.showError("Bad input: '" + userInput + "'");
            }
        }
    }//end inner class MultiplyListener


    //////////////////////////////////////////// inner class ClearListener
    /**  1. Reset model.
     *   2. Reset View.
     */    
    class ClearListener implements ActionListener {
        public void actionPerformed(ActionEvent e) {
            m_model.reset();
            m_view.reset();
        }
    }// end inner class ClearListener
}

模型

import java.math.BigInteger;

public class CalcModel {
    //... Constants
    private static final String INITIAL_VALUE = "0";

    //... Member variable defining state of calculator.
    private BigInteger m_total;  // The total current value state.

    //============================================================== constructor
    /** Constructor */
    CalcModel() {
        reset();
    }

    //==================================================================== reset
    /** Reset to initial value. */
    public void reset() {
        m_total = new BigInteger(INITIAL_VALUE);
    }

    //=============================================================== multiplyBy
    /** Multiply current total by a number.
    *@param operand Number (as string) to multiply total by.
    */
    public void multiplyBy(String operand) {
        m_total = m_total.multiply(new BigInteger(operand));
    }

    //================================================================= setValue
    /** Set the total value. 
    *@param value New value that should be used for the calculator total. 
    */
    public void setValue(String value) {
        m_total = new BigInteger(value);
    }

    //================================================================= getValue
    /** Return current calculator total. */
    public String getValue() {
        return m_total.toString();
    }
}


 类似资料:
  • Kafka集群中的Kafka控制器负责管理分区领导者和复制。 如果一个Kafka集群中有100个经纪商,控制器是否只是一个Kafka经纪商?那么在100个经纪商中,控制器是领导者吗? 你怎么知道哪个经纪人是控制人? Kafka控制器的管理对Kafka系统管理至关重要吗?

  • 这是的定义: 策略-定义了一系列算法,封装了每一个,并使它们可以互换。策略允许算法独立于使用它的客户端而变化。 所以,策略将功能分为两部分:一部分不会更改,另一部分在将来某个时间可以更改。 在MVC中,他们说: 控制器是视图的策略 这意味着控制器是变化的,视图将来可能不会改变。 我还不太明白。我认为他们两个将来都可以改变。 请给我解释一下人们为什么这么说。

  • 问题内容: 第一次遇到控制反转(IoC)时可能会造成很大的混乱。 它是什么? 它解决什么问题? 什么时候合适,什么时候不合适? 问题答案: 控制反转(IoC)和依赖注入(DI)模式都是关于从代码中删除依赖的。 例如,假设您的应用程序具有文本编辑器组件,而您想提供拼写检查。您的标准代码如下所示: 我们在这里所做的创建了和之间的依赖关系。在IoC场景中,我们改为执行以下操作: 在第一个代码示例中,我们

  • 你可以把一个版本控制系统(缩写VCS)理解为一个“数据库”,在需要的时候,它可以帮你完整地保存一个项目的快照。当你需要查看一个之前的快照(称之为“版本”)时,版本控制系统可以显示出当前版本与上一个版本之间的所有改动的细节。 版本控制与项目的种类,使用的技术和基础框架并无关系: 无论是设计开发一个HTML网站或者是一个苹果应用,它的工作原理都是一样的。 你可以选择任何你喜欢的工具来工作,它并不关心你

  • 问题内容: 有人可以告诉我如何在 不 使用声音库或合成器的 情况下 控制MIDI音序器的音量吗? 我想先使MIDI淡出,然后依次继续下一个MIDI 问题答案: 调用getSequence获得Sequence ; 调用getTracks获取曲目列表; 在每个轨道中,对于轨道中使用的每个频道,调用add在适当的时间位置添加多个事件: 也许从音轨中删除其他音量变化事件(这会干扰您的淡出效果); 等待一点

  • 我正在尝试使用Java并发和用于接口。 这意味着将有4个窗口,3个输入,一个输出。当您在3个GUI输入窗口中输入输入时,输出矩阵单元格将动态更改其值。我已经解决了程序的逻辑部分,但我仍然坚持使用swing显示接口,并将这两个东西绑定在一起? 在JavaSwing中表示矩阵的最佳布局是什么?从哪里开始学习这个?