如何将这个程序分成几个类

时间:2013-02-11 16:42:55

标签: java swing class

我使用Java Swing框架在Java中找到了这个简单计算器的实现。

源代码在这里:

//Imports are listed in full to show what's being used
//could just import javax.swing.* and java.awt.* etc..
import java.awt.EventQueue;
import java.awt.GridLayout;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.Container;

public class SimpleCalc implements ActionListener{

    JFrame guiFrame;
    JPanel buttonPanel;
    JTextField numberCalc;
    int calcOperation = 0;
    int currentCalc;

    //Note: Typically the main method will be in a
    //separate class. As this is a simple one class
    //example it's all in the one class.
    public static void main(String[] args) {

         //Use the event dispatch thread for Swing components
         EventQueue.invokeLater(new Runnable()
         {

            @Override
             public void run()
             {

                 new SimpleCalc();         
             }
         });

    }

    public SimpleCalc()
    {
        guiFrame = new JFrame();

        //make sure the program exits when the frame closes
        guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guiFrame.setTitle("Simple Calculator");
        guiFrame.setSize(300,300);

        //This will center the JFrame in the middle of the screen
        guiFrame.setLocationRelativeTo(null);

        numberCalc = new JTextField();
        numberCalc.setHorizontalAlignment(JTextField.RIGHT);
        numberCalc.setEditable(false);

        guiFrame.add(numberCalc, BorderLayout.NORTH);

        buttonPanel = new JPanel();

        //Make a Grid that has three rows and four columns
        buttonPanel.setLayout(new GridLayout(4,3));   
        guiFrame.add(buttonPanel, BorderLayout.CENTER);

        //Add the number buttons
        for (int i=1;i<10;i++)
        {
            addButton(buttonPanel, String.valueOf(i));
        }

        JButton addButton = new JButton("+");
        addButton.setActionCommand("+");

        OperatorAction subAction = new OperatorAction(1);
        addButton.addActionListener(subAction);

        JButton subButton = new JButton("-");
        subButton.setActionCommand("-");

        OperatorAction addAction = new OperatorAction(2);
        subButton.addActionListener(addAction);

        JButton equalsButton = new JButton("=");
        equalsButton.setActionCommand("=");
        equalsButton.addActionListener(new ActionListener()
        {
            @Override
            public void actionPerformed(ActionEvent event)
            {
                if (!numberCalc.getText().isEmpty())
                {
                    int number = Integer.parseInt(numberCalc.getText()); 
                    if (calcOperation == 1)
                    {
                        int calculate = currentCalc  + number;
                        numberCalc.setText(Integer.toString(calculate));
                    }
                    else if (calcOperation == 2)
                    {
                        int calculate = currentCalc  - number;
                        numberCalc.setText(Integer.toString(calculate));
                    }
                }
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(subButton);
        buttonPanel.add(equalsButton);
        guiFrame.setVisible(true);  
    }

    //All the buttons are following the same pattern
    //so create them all in one place.
    private void addButton(Container parent, String name)
    {
        JButton but = new JButton(name);
        but.setActionCommand(name);
        but.addActionListener(this);
        parent.add(but);
    }

    //As all the buttons are doing the same thing it's
    //easier to make the class implement the ActionListener
    //interface and control the button clicks from one place
    @Override
    public void actionPerformed(ActionEvent event)
    {
        //get the Action Command text from the button
        String action = event.getActionCommand();

        //set the text using the Action Command text
        numberCalc.setText(action);       
    }

    private class OperatorAction implements ActionListener
    {
        private int operator;

        public OperatorAction(int operation)
        {
            operator = operation;
        }

        public void actionPerformed(ActionEvent event)
        {
            currentCalc = Integer.parseInt(numberCalc.getText()); 
            calcOperation = operator;
        }
    }
}

我想把OperatorAction类放到一个单独的类中,我已经尝试了,但是从JTextField获取文本时出现问题,因为在新类中没有。那怎么会这样做呢?

2 个答案:

答案 0 :(得分:2)

您只需要另一个构造函数参数(以及匹配的实例字段):

class OperatorAction implements ActionListener
{
    private int operator;
    private SimpleCalc calc;

    public OperatorAction(SimpleCalc c, int operation)
    {
        calc = c;
        operator = operation;
    }

    public void actionPerformed(ActionEvent event) {
      calc.setCurrentCalc(Integer.parseInt( 
          ((JTextField)event.getSource()).getText()));
      calcOperation = operator;
    }
}

通过setter公开SimpleCalc#currentCalc属性。

这不是很干净的设计,因为OperatorActionSimpleCalc之间仍然存在紧密耦合,但它可能是你的开始。

答案 1 :(得分:-1)

看起来你需要使用模型视图控制器(MVC)模式! MVC是许多语言和系统不可或缺的组成部分,因此学习非常重要!你要做的是将程序分成3层,* M * odels,* V * iews,* C * ontrollers(在这种情况下,项目可能很简单,只能使用其中一个。)

模型将存储您的数据,这些数据可以是几个类,也可以是整个数据库,具体取决于项目的大小。

观看次数将显示您的数据。

控制器将管理其余部分。

所以你在这里做的是有一个模型只存储输入到计算器,一个控制器接受输入,做实际的数学运算,并将输出推送到视图。