What's new

Closed Refactoring series 1 - calculator

Status
Not open for further replies.

codyscott

Eternal Poster
Joined
Sep 13, 2017
Posts
388
Reaction
454
Points
279
Mga 'tol,
Isang demo ng code refactoring.
(pagandang or paiklihin ang code...yon lang yon)

Step 1. copy ang paste and run it... para makita yung ang itsura.
Step 2. then go back and READ....and UNDERSTAND the code
Step 3. Ang iyong premyo,....... CONCEPT

;)

********LONG METHOD***************
****Ito ay ginawa ko sa WindowBuilder***
Code:
/**
 * Long Method (very tedious)
 * Code para sa pag layout ng Calculator
 * by CodyScott for PHC
 * Just COPY AND PASTE.....and...Read and understand, are more important
 */
package com.cody.calc;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JButton;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class CalculatorLongMethod extends JFrame {

    /**
    * 
    */
    private static final long serialVersionUID = 1L;
    private JPanel buttonsPanel;

    /**
    * Create the frame.
    */
    public CalculatorLongMethod() {
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 230, 229);
        buttonsPanel = new JPanel();
        buttonsPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(buttonsPanel);
        buttonsPanel.setLayout(new MigLayout("", "[][][][]", "[][][][][]"));
       
        String initialDisplay = "0.0";
       
        JLabel display = new JLabel(initialDisplay);
        display.setHorizontalAlignment(SwingConstants.LEFT);
        display.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(display, "cell 0 0 4 1,alignx right");
       
        JButton btn7 = new JButton("7");
        btn7.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btn7.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btn7.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btn7, "cell 0 1");
       
        JButton btn8 = new JButton("8");
        btn8.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btn8.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btn8.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btn8, "cell 1 1");
       
        JButton btn9 = new JButton("9");
        btn9.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btn9.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btn9.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btn9, "cell 2 1");
       
        JButton btnDiv = new JButton("\u00F7");
        btnDiv.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btnDiv.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btnDiv.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btnDiv, "cell 3 1,alignx center");
       
        JButton btn4 = new JButton("4");
        btn4.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btn4.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btn4.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btn4, "cell 0 2");
       
        JButton btn5 = new JButton("5");
        btn5.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btn5.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btn5.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btn5, "cell 1 2");
       
        JButton btn6 = new JButton("6");
        btn6.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btn6.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btn6.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btn6, "cell 2 2");
       
        JButton btnMultiply = new JButton("x");
        btnMultiply.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btnMultiply.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btnMultiply.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btnMultiply, "cell 3 2,alignx center");
       
        JButton btn1 = new JButton("1");
        btn1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btn1.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btn1.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btn1, "cell 0 3");
       
        JButton btn2 = new JButton("2");
        btn2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btn2.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btn2.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btn2, "cell 1 3");
       
        JButton btn3 = new JButton("3");
        btn3.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btn3.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btn3.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btn3, "cell 2 3");
       
        JButton btnSubtract = new JButton("-");
        btnSubtract.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btnSubtract.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });

        btnSubtract.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btnSubtract, "cell 3 3");
       
        JButton btnAdd = new JButton("+");
        btnAdd.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            }
        });
       
        JButton btnC = new JButton("C");
        btnC.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                display.setText(initialDisplay);
            }
        });
        btnC.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btnC, "cell 0 4");
       
        JButton btn0 = new JButton("0");
        btn0.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int thisButton = Integer.parseInt(btn0.getText());
                if(display.getText().equals(initialDisplay)) {
                    display.setText("");
                }
                String newValue = display.getText() + thisButton;
                display.setText(newValue);
            }
        });
        btn0.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btn0, "cell 1 4");
       
        JButton button_13 = new JButton(".");
        button_13.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(button_13, "cell 2 4");
        btnAdd.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(btnAdd, "cell 3 4,alignx center");
    }

    /**************** ito yung mag la-launch ng app *******************/
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CalculatorLongMethod frame = new CalculatorLongMethod();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**************** ito yung mag la-launch ng app *******************/
   
}
/** TAKE NOTE: Kung paano niya ginawa yung mga buttons at i-arrange isa isa. Yan ang part na gagawan natin ng short method.  ****/


********SHORT METHOD*****************
****Kinuha ko yung gawa ng WindowBuilder***
***tapos ni-refactor ko ng konti************
Code:
/**
 * Short Method (little prettier).
 * Unang pass ng refactoring.
 * Code para sa pag layout ng Calculator
 * by CodyScott for PHC
  * Just COPY AND PASTE.....and...Read and understand, are more important
 */
package com.cody.calc;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.miginfocom.swing.MigLayout;
import javax.swing.JLabel;
import javax.swing.JButton;

import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.SwingConstants;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class CalculatorRefactored extends JFrame {
  
    //Ito yung mga labels ng lahat ng buttons
    static String[] buttons = {"7","8","9","\u00F7","4","5","6","x","1","2","3","-","C","0",".","+"};


    private JPanel buttonsPanel;

    /**
    * Ito yung constructor. Gagawa siya ng Frame, then Panel para lalagyan ng mga Buttons
    * Then kakargahan niya ng buttons and action para sa mga buttons, etc. etc.
    */
    public CalculatorRefactored() {
        setTitle("Calculator 2.0");
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 230, 229);
        buttonsPanel = new JPanel();
        buttonsPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(buttonsPanel);
        buttonsPanel.setLayout(new MigLayout("", "[][][][]", "[][][][][]"));
      
        //ito yung idi-display ng screen ng calculator sa umpisa
        String initialDisplay = "0.0";
      
        //ito yung kungyari screen ng calculator
        JLabel display = new JLabel(initialDisplay);
        display.setHorizontalAlignment(SwingConstants.LEFT);
        display.setFont(new Font("Tahoma", Font.PLAIN, 18));
        buttonsPanel.add(display, "cell 0 0 4 1,alignx right");
      

        /**
        * Ito ay maglo-loop siya para gumawa ng mga buttons
        * tapos ang number ng loops niya ay
        * depende sa dami ng laman ng buttons array sa taas
        */
        int row = 1;    //row 1 magsisimula
        int col = 0;    //unang colum
        for(int i=0; i<buttons.length; i++) {
            String buttonLabel = buttons[i];                                    //1. kukuha ng button name; halimbawa "7"
            JButton newButton = new JButton(buttonLabel);                        //2. gagawa ng isang instance ng JButton at ilalagay button label

            newButton.addActionListener(new ActionListener() {                    //3. tapos kakabitan ng actionListener para pag pinindut ay gagawa siya ng action.
                public void actionPerformed(ActionEvent e) {                    //    Ito yung action na gagawin niya.
                    int thisButton = Integer.parseInt(newButton.getText());        //
                    if(display.getText().equals(initialDisplay)) {                //
                        display.setText("");                                    //
                    }                                                            //
                    String newValue = display.getText() + thisButton;            //
                    display.setText(newValue);                                    //
                }                                                                //
            });                                                                    //dito mag e-end ng declare ng actionListener
          
            newButton.setFont(new Font("Tahoma", Font.PLAIN, 18));                //4. Pampaganda ng fonts lang ito
          
            if(col>3) {                                                            //5. Dahil alam natin na 4 colums and 5 rows ang arrangement ng mga buttons
                col=0;                                                            //  ito yung mag a-arrange. Pag na reach ang 4 column,
                row++;                                                            //  mag ne-next row siya ang first column uli siya magsisimula
            }                                                                    //
            String position = "cell " + col + " " + row;                        //
            buttonsPanel.add(newButton, position);                                //
            col++;                                                                // hanggang dito
        }
      
        // ***** from here, balik uli siya sa umpisa ng for loop.
    }

    /**************** ito yung mag la-launch ng app *******************/
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CalculatorRefactored frame = new CalculatorRefactored();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
    /**************** ito yung mag la-launch ng app *******************/
  
}
/** TAKE NOTE: This is just the initial setup. May mga exception errors pa. This is just a demonstration on how to make your code PRETTY ****/
 
Status
Not open for further replies.

Similar threads

Back
Top