四則運算GUI版本

blogli發表於2016-10-19

要求:使用者介面新增支援 Windows GUI,同時保留原有命令列下所有功能。提示: 先測試驅動開發,然後重構程式碼,以GUI為目標修改"核心"函式,把與GUI/Console相關的部分提取出來
在原來實現四則運算的基礎上通過java中的Swing元件實現了GUI版本
GUI的實現程式碼如下

public class CalMachineSwingBuild extends JFrame {

    private JPanel contentPane; 
    private JComboBox comboBox;
    private JLabel lblNewLabel; 
    private JTextField textField;
    private JLabel lblNewLabel_1;
    private ArrayList<String> questionList=new ArrayList<String>();
    private ArrayList<JTextField> answersByUser = new ArrayList<JTextField>(); //存放使用者填寫的答案的文字域
    private ArrayList<String> RealAnswerList=new ArrayList<String>();  //存放真正的答案
    private String strAnswerAndResult[]=new String[2];
    private JLabel label_1;
    private JLabel lblNewLabel_3;
    private JButton submitButton;
    private JPanel panelNorth;
    private JPanel panelCenter;
    private JPanel panelSouth;
    private static int numOfQuestion; //問題的數量
    private String itemValue;   //難度級別
    private String recordWrong=" ";
    private String userName;
    private int countWrong=0;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    CalMachineSwingBuild frame = new CalMachineSwingBuild();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public CalMachineSwingBuild() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 800, 600);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane); 
        contentPane.setLayout(new BorderLayout(0, 0));
        panelNorth=new JPanel();
        JLabel label = new JLabel("難度值");
        label.setBounds(10, 10, 42, 15);
        panelNorth.add(label);
        //contentPane.add(label); 
        
        comboBox = new JComboBox();
        comboBox.addItem("簡單");
        comboBox.addItem("普通");
        comboBox.addItem("複雜"); 
        comboBox.setBounds(62, 7, 50, 100);
        comboBox.setEditable(false);    
        comboBox.setSize(60, 20); 
        panelNorth.add(comboBox);
        // contentPane.add(comboBox); 
         
         lblNewLabel = new JLabel("題目數量");
         lblNewLabel.setBounds(144, 10, 62, 15);
         panelNorth.add(lblNewLabel);
        // contentPane.add(lblNewLabel);
         
         textField = new JTextField();
         textField.setBounds(216, 7, 46, 21);
        // contentPane.add(textField);
         textField.setColumns(10);
         panelNorth.add(textField);
         
         JButton btnNewButton = new JButton("開始出題");
         btnNewButton.setBounds(272, 6, 93, 23); 
        /* labelForSpec=new  JLabel();
         panelNorth.add(labelForSpec);*/
         panelNorth.add(btnNewButton);
         contentPane.add(panelNorth,BorderLayout.NORTH);  
         
         panelSouth=new JPanel();
         lblNewLabel_1 = new JLabel();  //用作提示
         submitButton = new JButton("提交答案");//提交按鈕
         panelSouth.add(lblNewLabel_1);
         panelSouth.add(submitButton);
         contentPane.add(panelSouth,BorderLayout.SOUTH);
         
         panelCenter=new JPanel();
         contentPane.add(panelCenter,BorderLayout.CENTER);
         panelCenter.setLayout(new MigLayout("", "[][grow]", "[][]"));
         
         btnNewButton.addMouseListener(new MouseAdapter() { 
            @Override
            public void mouseClicked(MouseEvent event) {
                repaint(); //重新展示介面
                panelCenter.removeAll();
                questionList.clear();
                answersByUser.clear();   
                Pattern pattern = Pattern.compile("^+?[1-9][0-9]*$");  
                Matcher isNum = pattern.matcher(textField.getText());   
                if(!isNum.matches()){
                    lblNewLabel_1.setText("輸入的題目數必須為整數!");
                }else{
                    lblNewLabel_1.setText(""); 
                    itemValue=(String) comboBox.getSelectedItem(); 
                    numOfQuestion=Integer.parseInt(textField.getText());
                    CalMachine cm=new CalMachine();
                    CalculateMachine04 cm04=new CalculateMachine04();
                    switch(itemValue){
                    case "簡單": 
                        questionList=(ArrayList<String>) cm.addBracketTest(numOfQuestion);
                        
                        for(int i=0;i<questionList.size();i++){
                              JLabel questionBar = new JLabel();
                             panelCenter.add(questionBar, "cell 0 " + i + ",alignx trailing");
                            JTextField answerBar = new JTextField("", 10);
                            panelCenter.add(answerBar, "cell 1 " + i + " ,alignx trailing");
                            strAnswerAndResult=questionList.get(i).split("="); //前者為問題,後者為答案
                            questionBar.setText("question"+(i+1)+":     "+strAnswerAndResult[0]); 
                            RealAnswerList.add(strAnswerAndResult[1]);  //存放真正的答案
                            answersByUser.add(answerBar); 
                        }
                        break;
                    case "普通":
                        questionList=(ArrayList<String>) cm.generateSimpleQuestion(numOfQuestion);
                        for(int i=0;i<questionList.size();i++){
                              JLabel questionBar = new JLabel();
                             panelCenter.add(questionBar, "cell 0 " + i + ",alignx trailing");
                            JTextField answerBar = new JTextField("", 10);
                            panelCenter.add(answerBar, "cell 1 " + i + " ,alignx trailing");
                            strAnswerAndResult=questionList.get(i).split("="); //前者為問題,後者為答案
                            questionBar.setText("question"+(i+1)+":     "+strAnswerAndResult[0]); 
                            RealAnswerList.add(strAnswerAndResult[1]);  //存放真正的答案
                            answersByUser.add(answerBar); 
                        }
                        break;
                    case "複雜": 
                        questionList=(ArrayList<String>) cm04.generateComplexQuestion(numOfQuestion);
                        for(int i=0;i<questionList.size();i++){
                              JLabel questionBar = new JLabel();
                             panelCenter.add(questionBar, "cell 0 " + i + ",alignx trailing");
                            JTextField answerBar = new JTextField("", 10);
                            panelCenter.add(answerBar, "cell 1 " + i + " ,alignx trailing");
                            strAnswerAndResult=questionList.get(i).split("="); //前者為問題,後者為答案
                            questionBar.setText("question"+(i+1)+":     "+strAnswerAndResult[0]); 
                            RealAnswerList.add(strAnswerAndResult[1]);  //存放真正的答案
                            answersByUser.add(answerBar); 
                        }
                        break;
                    }
                    System.out.println();
                }
            }
        });
         //提交判斷
         submitButton.addActionListener(new ActionListener() { 
            @Override
            public void actionPerformed(ActionEvent e) { 
                
                 for(int i=0;i<numOfQuestion;i++){
                     if(!answersByUser.get(i).getText().trim().equals(RealAnswerList.get(i))){
                         //使用者答錯了
                         recordWrong+=(i+1)+",";
                         countWrong++;
                     }
                 }
              if(recordWrong.length()>1){
                     lblNewLabel_1.setText("第"+recordWrong+"題答錯了!"); 
                 }else if(textField.getText().length()==0){
                     lblNewLabel_1.setText("請輸入題數!");
                 } else{
                     lblNewLabel_1.setText("恭喜你,全都搭對了!");
                 }
                 
            /*     if(e.getSource()==submitButton){ 
                     System.out.println("點選了"+itemValue);
                     new CalMachineSwingBuildResult(userName,itemValue,numOfQuestion
                             ,countWrong,numOfQuestion-countWrong).show();;
                 }*/
                
                 recordWrong="";
                
            }
        });
    }

}

執行介面如下:

ssh:git@git.coding.net:muziliquan/GUIVersion.git

git:git://git.coding.net/muziliquan/GUIVersion.git

 

相關文章