本代码来自川师java实训,包结构在截图里面,resource里面是放的所有的图片,然后包截图里面有一个text的文件夹是放的property和那三个txt文件的,PS:有什么不懂得可以私我~
- package com.tarena.elts.util;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.util.Properties;
- /**
- * Created by EnderSnow on 2016/7/7.
- * Time:10:14
- * ${DESCRIPTION}
- * ${FILE_NAME}
- */
- public class Config {
- private Properties table = new Properties();
- /* 给table赋值*/
- public Config(String filename) {
- try {
- table.load(new InputStreamReader(new FileInputStream(filename),"utf-8"));
- } catch (FileNotFoundException e) {
- System.out.println("can't find you properties file");//load thrown
- } catch (IOException e) {
- e.printStackTrace();//fileInputStream thrown
- }
- }
- public int getInt(String key) {//get the value of int
- return Integer.parseInt(table.getProperty(key));
- }
- public double getDouble(String key) {//get the value of double
- return Double.parseDouble(table.getProperty(key));
- }
- public String getString(String key) {//get the value of String
- return table.getProperty(key);
- }
- }
复制代码
- package com.tarena.elts.ui;
- import javax.swing.*;
- import javax.swing.border.Border;
- import java.awt.*;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- /**
- * Created by EnderSnow on 2016/7/6.
- * Time:9:20
- * ${DESCRIPTION} menu frame
- * ${FILE_NAME}
- */
- public class MenuFrame extends JFrame {
- private JLabel informationLabel;
- public MenuFrame() {
- init();
- }
- private ClientContext clientContext;
- public void setClientContext(ClientContext clientContext) {
- this.clientContext = clientContext;
- }
- /**
- * frame init
- */
- private void init() {
- this.setTitle("Ender E-Learning Test System");
- this.setSize(880, 583);
- this.setLocationRelativeTo(null);//siting the frame in center
- this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- this.setContentPane(createContentPanel());
- this.addWindowListener(new WindowAdapter() {
- @Override
- public void windowClosing(WindowEvent e) {
- clientContext.exit(MenuFrame.this);
- }
- });
- }
- /**
- * create the main content pane
- *
- * @return mainJPanel
- */
- private Container createContentPanel() {
- JPanel mainJPanel = new JPanel();
- mainJPanel.setLayout(new BorderLayout());
- mainJPanel.add(BorderLayout.NORTH, createTitleImagePanel());
- mainJPanel.add(BorderLayout.CENTER, createBtnImagePanel());
- mainJPanel.add(BorderLayout.SOUTH, createNoticePanel());
- return mainJPanel;
- }
- /**
- * create image title area
- *
- * @return ImageLabel
- */
- private Component createTitleImagePanel() {
- return new JLabel(new ImageIcon("resource/title2.png"));
- }
- private Component createBtnImagePanel() {
- JPanel btnPanel = new JPanel();
- btnPanel.setLayout(new BorderLayout());
- btnPanel.add(BorderLayout.NORTH, createInfoLabel());
- btnPanel.add(BorderLayout.CENTER, createBtnPanel());
- return btnPanel;
- }
- private Component createBtnPanel() {
- JPanel buttonPanel = new JPanel();
- buttonPanel.setLayout(new GridLayout(1, 4, 5, 5));
- JButton startBtn = createImageButton("resource/start.png", "Start Exam");
- JButton checkBtn = createImageButton("resource/score.png", "CheckScore");
- JButton waringBtn = createImageButton("resource/rule.png", "Notice Advice");
- JButton exitBtn = createImageButton("resource/exit.png", "Exit System");
- buttonPanel.add(startBtn);
- buttonPanel.add(checkBtn);
- buttonPanel.add(waringBtn);
- buttonPanel.add(exitBtn);
- //给开始考试按钮添加事件,该事件触发后调用ClientContext的start()
- startBtn.addActionListener(e -> clientContext.start());
- checkBtn.addActionListener(e -> clientContext.check());
- waringBtn.addActionListener(e -> clientContext.waring());
- exitBtn.addActionListener(e -> clientContext.exit(MenuFrame.this));
- return buttonPanel;
- }
- /**
- * create Info label
- *
- * @return informationLabel
- */
- private Component createInfoLabel() {
- informationLabel = new JLabel();
- informationLabel.setText("welcome to you,");
- informationLabel.setHorizontalAlignment(JLabel.CENTER);
- return informationLabel;
- }
- //update menu info label
- void updateInfo(String username) {
- informationLabel.setText("welcome to you," + username);
- }
- /**
- * create noticePanel
- *
- * @return NoticeJlabel
- */
- private Component createNoticePanel() {
- return new JLabel("all Rights Reserved-infringement", JLabel.RIGHT);
- }
- private JButton createImageButton(String iconPath, String msg) {
- ImageIcon icon = new ImageIcon(iconPath);
- JButton button = new JButton(msg, icon);
- Border b1 = BorderFactory.createLineBorder(Color.orange, 2);
- Border b2 = BorderFactory.createEmptyBorder(15, 5, 15, 5);
- button.setBorder(BorderFactory.createCompoundBorder(b1, b2));
- //将文本垂直方向底部对齐
- button.setVerticalTextPosition(JButton.BOTTOM);
- //将文本水平方向居中对齐
- button.setHorizontalTextPosition(JButton.CENTER);
- button.setOpaque(false);
- // button.setBorderPainted(false);
- return button;
- }
- /*add attribute of ClientContext,for this class calling control function调用控制器方法*/
- }
复制代码
- package com.tarena.elts.ui;
- import javax.swing.*;
- import javax.swing.border.EmptyBorder;
- import java.awt.*;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- /**
- * Created by EnderSnow on 2016/7/6.
- * Time:9:20
- * ${DESCRIPTION} Login Frame
- * ${FILE_NAME}
- */
- public class LoginFrame extends JFrame {
- /*add property*/
- private ClientContext clientContext;
- private JTextField idTextFiled;
- private JPasswordField passwordField;
- private JLabel noticeLabel;
- private JPanel idPwdPanel;
- public LoginFrame() {
- init();
- }
- /**
- * initialize main frame
- */
- private void init() {
- this.setResizable(false);
- this.setTitle("Login");
- this.setSize(900, 590);
- this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
- this.setLocationRelativeTo(null);
- this.setContentPane(createContentPane());
- this.addWindowListener(new WindowAdapter() {
- @Override
- public void windowClosing(WindowEvent e) {
- clientContext.exit(LoginFrame.this);
- }
- });
- }
- /**
- * create mainPanel logic
- */
- private Container createContentPane() {
- JPanel mainPanel = new JPanel() {
- private static final long serialVersionUID = 1L;
- @Override
- protected void paintComponent(Graphics g) {
- super.paintComponent(g);
- g.drawImage(new ImageIcon(
- "resource/login.png").getImage(), 0,
- 0, getWidth(), getHeight(), null);
- }
- };
- mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
- mainPanel.setLayout(new BorderLayout());
- mainPanel.add(BorderLayout.NORTH, new JLabel("LoginSystem", JLabel.CENTER));
- mainPanel.add(BorderLayout.CENTER, createCenterPane());
- mainPanel.add(BorderLayout.SOUTH, createBtnPane());
- mainPanel.setOpaque(false);
- return mainPanel;
- }
- /**
- * create south button area
- *
- * @return BtnPanel
- */
- private Component createBtnPane() {
- JPanel btnPanel = new JPanel(new FlowLayout()) {
- private static final long serialVersionUID = 1L;
- @Override
- protected void paintComponent(Graphics g) {
- super.paintComponent(g);
- g.drawImage(new ImageIcon(
- "resource/button.png").getImage(), 0,
- 0, getWidth(), getHeight(), null);
- }
- };
- JButton loginBtn = new JButton("Login");
- JButton cancelBtn = new JButton("Cancel");
- JButton noButton = new JButton();
- noButton.setBorderPainted(false);
- noButton.setContentAreaFilled(false);
- btnPanel.add(loginBtn);
- btnPanel.add(noButton);
- btnPanel.add(cancelBtn);
- loginBtn.addActionListener(e -> clientContext.Login());
- loginBtn.setOpaque(false);
- loginBtn.setBackground(Color.gray);
- loginBtn.setContentAreaFilled(false);
- loginBtn.setFont(new Font("微软雅黑", Font.BOLD, 12));
- loginBtn.setForeground(Color.YELLOW);
- cancelBtn.addActionListener(e -> clientContext.exit(LoginFrame.this));
- cancelBtn.setOpaque(false);
- cancelBtn.setBackground(Color.gray);
- cancelBtn.setContentAreaFilled(false);
- cancelBtn.setFont(new Font("微软雅黑", Font.BOLD, 12));
- cancelBtn.setForeground(Color.YELLOW);
- btnPanel.setOpaque(false);
- //loginBtn.setBounds();
- return btnPanel;
- }
- /**
- * create center ID and PWD area
- *
- * @return CenterPanel
- */
- private Component createCenterPane() {
- JPanel centerPanel = new JPanel(new BorderLayout());
- centerPanel.add(BorderLayout.CENTER, createFiledPane());
- centerPanel.add(BorderLayout.SOUTH, createNoticePane());
- centerPanel.setOpaque(false);
- return centerPanel;
- }
- /**
- * create notice label
- *
- * @return jLabel
- */
- private Component createNoticePane() {
- noticeLabel = new JLabel();
- noticeLabel.setText("try login?");
- noticeLabel.setHorizontalAlignment(JLabel.CENTER);
- return noticeLabel;
- }
- /**
- * create id and pwd Panel
- *
- * @return IdPwdPanel
- */
- private Component createFiledPane() {
- //idPwdPanel = new JPanel(new GridLayout(2, 1, 0, 15));
- idPwdPanel = new JPanel();
- idPwdPanel.setLayout(null);
- idPwdPanel.add(createIdPane());
- idPwdPanel.setOpaque(false);
- idPwdPanel.add(createPwdPane());
- idPwdPanel.setAlignmentY(JPanel.CENTER_ALIGNMENT);
- // idPwdPanel.setBounds(410,330,320,45);
- return idPwdPanel;
- }
- /**
- * create ID input panel;
- *
- * @return IDPanel
- */
- private Component createIdPane() {
- JPanel idPanel = new JPanel(new BorderLayout());
- //idPanel.setForeground(Color.red);
- JLabel idLabel = new JLabel();
- idLabel.setOpaque(false);
- JTextField idTextFiled = new JTextField();
- this.idTextFiled = idTextFiled;
- idPanel.add(BorderLayout.WEST, idLabel);
- idPanel.add(BorderLayout.CENTER, idTextFiled);
- idPanel.setOpaque(false);
- idTextFiled.setOpaque(false);
- idPanel.setBounds(413, 210, 143, 25);
- return idPanel;
- }
- /*gain idField text*/
- String getUserId() {
- return idTextFiled.getText();
- }
- /**
- * create Password input panel
- *
- * @return pwdPanel
- */
- private Component createPwdPane() {
- JPanel pwdPanel = new JPanel(new BorderLayout());
- JLabel pwdLabel = new JLabel();
- pwdLabel.setOpaque(false);
- JPasswordField passwordField = new JPasswordField();
- this.passwordField = passwordField;
- pwdPanel.add(BorderLayout.WEST, pwdLabel);
- pwdPanel.add(BorderLayout.CENTER, passwordField);
- pwdPanel.setOpaque(false);
- passwordField.setOpaque(false);
- pwdPanel.setBounds(413, 245, 143, 25);
- return pwdPanel;
- }
- //gain user Password
- String getUserPwd() {
- char temp[] = passwordField.getPassword();
- return new String(temp);
- }
- /*add set methed to property for outside calling,to attribute for object injection,keep your project only one target,*/
- public void setClientContext(ClientContext clientContext) {
- this.clientContext = clientContext;
- }
- //show wrong message
- void showMessage(String message) {
- noticeLabel.setForeground(Color.RED);
- noticeLabel.setText(message);//noticeLabel 's setText methed
- }
- }
复制代码
- package com.tarena.elts.ui;
- import com.tarena.elts.entitiv.ExamInfo;
- import com.tarena.elts.entitiv.QuestionInfo;
- import javax.swing.*;
- import javax.swing.border.EmptyBorder;
- import javax.swing.border.TitledBorder;
- import java.awt.*;
- import java.awt.event.WindowAdapter;
- import java.awt.event.WindowEvent;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * Created by EnderSnow on 2016/7/6.
- * Time:9:19
- * ${DESCRIPTION} Exam frame
- * ${FILE_NAME}
- */
- public class ExamFrame extends JFrame {
- public ExamFrame() {
- init();
- }
- /**
- * initialise ExamFrame
- */
- private void init() {
- this.setTitle("Ender Technology Online Exam");
- this.setSize(800, 700);
- this.setLocationRelativeTo(null);
- this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
- this.setContentPane(createContentPanel());
- this.addWindowListener(new WindowAdapter() {
- @Override
- public void windowClosing(WindowEvent e) {
- clientContext.submit();
- }
- });
- }
- /**
- * create ContentPanel
- *
- * @return mainPanel
- */
- private Container createContentPanel() {
- JPanel mainPanel = new JPanel();
- mainPanel.setLayout(new BorderLayout());
- mainPanel.add(BorderLayout.NORTH, createtitleImagePanel());
- mainPanel.add(BorderLayout.CENTER, createQuestionFiled());
- mainPanel.add(BorderLayout.SOUTH, createToolPanel());
- return mainPanel;
- }
- /**
- * create title Image
- *
- * @return Jlabel
- */
- private Component createtitleImagePanel() {
- // imageLabel.setSize(new Dimension(800,370));
- return new JLabel(new ImageIcon("resource/exam_title2.png"));
- }
- /**
- * create question Area
- *
- * @return QuestionPanel
- */
- private Component createQuestionFiled() {
- JPanel QuestionPanel = new JPanel();
- QuestionPanel.setLayout(new BorderLayout());
- QuestionPanel.add(BorderLayout.NORTH, createInfoLabel());
- QuestionPanel.add(BorderLayout.CENTER, createQuestionPanel());
- QuestionPanel.add(BorderLayout.SOUTH, createOptionPanel());
- return QuestionPanel;
- }
- /**
- * create center qustion field
- *
- * @return QuestionPanel
- */
- private JTextArea qusetionArea;
- private Component createQuestionPanel() {
- JScrollPane QuestionPanel = new JScrollPane();
- QuestionPanel.setBorder(new TitledBorder("problems-"));
- qusetionArea = new JTextArea(6, 15);
- qusetionArea.setBorder(new EmptyBorder(3, 3, 3, 3));
- qusetionArea.setLineWrap(true);//anto wrap line
- qusetionArea.setEditable(false);//set this area is uneditable
- QuestionPanel.getViewport().add(qusetionArea);
- return QuestionPanel;
- }
- /**
- * create chosenPanel
- *
- * @return chosenPanel
- */
- private Option a;
- private Option b;
- private Option c;
- private Option d;
- private Component createOptionPanel() {
- JPanel chosenPanel = new JPanel();
- // ButtonGroup buttonGroup = new ButtonGroup();
- a = new Option(0, "A");
- b = new Option(1, "B");
- c = new Option(2, "C");
- d = new Option(3, "D");
- chosenPanel.add(a);
- chosenPanel.add(b);
- chosenPanel.add(c);
- chosenPanel.add(d);
- //chosenPanel.add(select);
- return chosenPanel;
- }
- private JLabel infoLabel;
- /**
- * create personal Info Label
- *
- * @return infoLabel
- */
- private Component createInfoLabel() {
- infoLabel = new JLabel();
- infoLabel.setText("name:xxx id:0527 subject: java ExamTime: 60 min");
- infoLabel.setHorizontalAlignment(JLabel.CENTER);
- return infoLabel;
- }
- /**
- * create tool Panel
- *
- * @return toolBtnPanel
- */
- private Component createToolPanel() {
- JPanel toolBtnPanel = new JPanel() {
- private static final long serialVersionUID = 1L;
- @Override
- protected void paintComponent(Graphics g) {
- super.paintComponent(g);
- g.drawImage(new ImageIcon(
- "resource/button2.png").getImage(), 0,
- 0, getWidth(), getHeight(), null);
- }
- };
- toolBtnPanel.setLayout(new BorderLayout());
- toolBtnPanel.add(BorderLayout.WEST, createProLabel());
- toolBtnPanel.add(BorderLayout.CENTER, createToolBtn());
- toolBtnPanel.add(BorderLayout.EAST, createTimeLabel());
- return toolBtnPanel;
- }
- /**
- * create toolBtn area
- *
- * @return toolBtn
- */
- private Component createToolBtn() {
- JPanel toolBtn = new JPanel();
- toolBtn.setOpaque(false);
- toolBtn.setForeground(Color.cyan);
- JButton backBtn = new JButton("back");
- JButton nextBtn = new JButton("next");
- JButton submitBtn = new JButton("Submit");
- backBtn.setOpaque(false);
- nextBtn.setOpaque(false);
- submitBtn.setOpaque(false);
- toolBtn.add(backBtn);
- toolBtn.add(nextBtn);
- toolBtn.add(submitBtn);
- //给下一题按钮添加事件,此事件触发后调用控制器的next()
- nextBtn.addActionListener(e -> clientContext.next());
- backBtn.addActionListener(e -> clientContext.back());
- submitBtn.addActionListener(e -> clientContext.submit());
- return toolBtn;
- }
- List<Integer> getOptionStatus() {//to gain user's optionsList
- ArrayList<Integer> answersList = new ArrayList<>();
- if (a.isSelected()) {
- answersList.add(a.value);
- }
- if (b.isSelected()) {
- answersList.add(b.value);
- }
- if (c.isSelected()) {
- answersList.add(c.value);
- }
- if (d.isSelected()) {
- answersList.add(d.value);
- }
- //System.out.println(answersList);
- return answersList;
- }
- /**
- * create problem Notice label
- *
- * @return proLabel
- */
- private JLabel proLabel;
- private Component createProLabel() {
- JPanel proPanel = new JPanel(new FlowLayout());
- proPanel.setPreferredSize(new Dimension(150,10));
- proLabel = new JLabel();
- proLabel.setText("NO.x in Paper");
- proPanel.add(proLabel);
- proLabel.setHorizontalAlignment(JLabel.LEFT);
- proPanel.setOpaque(false);
- return proPanel;
- }
- /**
- * create leftTime notice label
- *
- * @return leftLabel
- */
- private JLabel leftLabel;
- private Component createTimeLabel() {
- JPanel timePanel = new JPanel(new FlowLayout());
- setPreferredSize(new Dimension(100,10));
- leftLabel = new JLabel();
- leftLabel.setText("Remaining Time:");
- leftLabel.setHorizontalAlignment(JLabel.RIGHT);
- timePanel.add(leftLabel);
- timePanel.setOpaque(false);
- return timePanel;
- }
- void updateRemaingTime(int time) {
- if (time == 0){
- clientContext.submit();
- clientContext.cancel();
- }
- String dateString = String.format("%02d:%02d:%02d", time / 3600,
- time / 60, time % 60);
- leftLabel.setText("Remaining Time:"+dateString);
- }
- /* 内部类 扩展API的多选框 有int类型的value参数,代表答案传给服务器*/
- private class Option extends JCheckBox {
- int value;
- Option(int value, String text) {
- super(text);//call super construction methed that carry one paremeter
- this.value = value;
- }
- }
- private void clearOptions() {
- a.setSelected(false);
- b.setSelected(false);
- c.setSelected(false);
- d.setSelected(false);
- }
- void updateView(ExamInfo start, QuestionInfo questionInfo) {
- clearOptions();
- infoLabel.setText(start.toString());
- qusetionArea.setText(questionInfo.toString());
- // System.out.println(questionInfo.getQuestionIndex());
- proLabel.setText("NO." + questionInfo.getQuestionIndex() + " in this paper");
- }
- /**
- * refactoring updateView
- * update questionInfo and optionStatus
- */
- void updateView(QuestionInfo questionInfo, List<Integer> answering) {
- clearOptions();
- qusetionArea.setText(questionInfo.toString());
- proLabel.setText("NO." + questionInfo.getQuestionIndex() + " in this paper");
- for (Integer i : answering) {
- switch (i) {
- case 0:
- a.setSelected(true);
- break;
- case 1:
- b.setSelected(true);
- break;
- case 2:
- c.setSelected(true);
- break;
- case 3:
- d.setSelected(true);
- break;
- }
- }
- }
- /**
- * 添加updateView(ExamInfo e,QuestionInfo q)
- * 把考试信息给该界面中的ExamArea(考题区面板)
- * 把QuestionInfo的信息给奔雷当中的QuestionArea
- * 把第几题给本类当中的左下角的proLabel
- */
- /*添加控制器属性,便于本类访问控制器方法*/
- private ClientContext clientContext;
- /*添加对象注入的set方法*/
- public void setClientContext(ClientContext clientContext) {
- this.clientContext = clientContext;
- }
- }
复制代码
- package com.tarena.elts.ui;
- import com.tarena.elts.entitiv.ExamInfo;
- import com.tarena.elts.entitiv.QuestionInfo;
- import com.tarena.elts.entitiv.User;
- import com.tarena.elts.service.ExamService;
- import com.tarena.elts.service.IDorPWDException;
- import javax.swing.*;
- import java.awt.*;
- import java.util.*;
- import java.util.Timer;
- ;
- /**
- * Created by EnderSnow on 2016/7/8.
- * Time:9:25
- * ${DESCRIPTION} the control between frame and model
- * ${FILE_NAME}
- */
- public class ClientContext {
- /**
- * login
- * 1.gain user ID and PWD
- * 2.call model login methed,finish user login
- * 3.according result,update frame,show user information
- * closing login frame,open menu frame,
- * 4.if login failed,show failed message
- */
- private LoginFrame loginframe;
- //登录界面对象的应用,达到控制器能够操作登录界面
- public void setLoginFrame(LoginFrame loginframe) {
- this.loginframe = loginframe;
- }
- private MenuFrame menuFrame;
- //菜单界面对象的应用,达到控制器能够操作菜单界面
- public void setMenuFrame(MenuFrame menuFrame) {
- this.menuFrame = menuFrame;
- }
- private ExamService examService;
- //增加业务模型实现的属性,达到控制器调用业务模型中的方法
- public void setExamService(ExamService examService) {
- this.examService = examService;
- }
- void Login() {
- try {
- String userId = loginframe.getUserId();//gain Id
- String userPwd = loginframe.getUserPwd();//gain password
- User user = examService.Login(Integer.parseInt(userId), userPwd);
- //update menu frame
- menuFrame.updateInfo(user.getName());
- loginframe.dispose();//closing login frame
- menuFrame.setVisible(true);//show menu frame
- } catch (IDorPWDException e) {
- //执行用户Id和PWD错误的逻辑
- loginframe.showMessage("login failed" + e.getMessage());
- e.printStackTrace();
- } catch (NumberFormatException e) {
- loginframe.showMessage("your id should be Integer");
- } catch (Exception e) {
- loginframe.showMessage("login failed" + e.getMessage());
- }
- }
- //frame show
- public void show() {
- loginframe.setVisible(true);
- }
- //close frame
- void exit(Component from) {
- int res = JOptionPane.showConfirmDialog(from, "are you sure to leave?", "please ensure", JOptionPane.YES_NO_OPTION);
- if (res == JOptionPane.YES_OPTION) {
- System.exit(0);
- }
- }
- //添加考试界面的属性
- private ExamFrame examFrame;
- //添加考试界面的set方法
- public void setExamFrame(ExamFrame examFrame) {
- this.examFrame = examFrame;
- }
- //定义开始考试的start方法
- //调用ExamService的start(),返回ExamInfo,包含考试信息,
- //调用ExamService的getQuestionInfo(0),获得一道考题,用于更新考试界面,
- //更新考试界面,调用考试界面的更新方法updateView(ExamInfo e,QuestionInfo q)
- //关闭菜单界面
- //显示考试界面
- private int countIndex = 0;
- private QuestionInfo questionInfo = new QuestionInfo();
- void start() {
- try {
- ExamInfo start = examService.start();
- questionInfo = examService.getQuestionInfo(countIndex);
- examFrame.updateView(start, questionInfo);
- menuFrame.setVisible(false);
- examFrame.setVisible(true);
- updateTime();
- } catch (Exception e) {
- JOptionPane.showMessageDialog(menuFrame,e.getMessage());
- }
- }
- private java.util.Timer timer;
- private void updateTime(){
- TimerTask timerTask = new TimerTask() {
- private int i = 0;
- @Override
- public void run() {
- examFrame.updateRemaingTime(examInfo.getTimeLimit()*60 -i );
- ++i;
- }
- };
- timer = new Timer();
- timer.schedule(timerTask,0,1000);
- }
- void cancel(){
- timer.cancel();
- System.out.println("已经关闭timer");
- }
- private ExamInfo examInfo = new ExamInfo();
- void next() {
- countIndex = examService.next(countIndex, examFrame.getOptionStatus());
- questionInfo = examService.getQuestionInfo(countIndex);
- examFrame.updateView(questionInfo, questionInfo.getAnswers());
- }
- void back() {
- countIndex = examService.back(countIndex, examFrame.getOptionStatus());
- questionInfo = examService.getQuestionInfo(countIndex);
- //System.out.println(questionInfo.getAnswers());
- examFrame.updateView(questionInfo, questionInfo.getAnswers());
- }
- public void setExamInfo(ExamInfo examInfo) {
- this.examInfo = examInfo;
- }
- void submit() {
- examService.next(countIndex, examFrame.getOptionStatus());
- int i = JOptionPane.showConfirmDialog(examFrame, "ensure to submit", "please ensure to submit?", JOptionPane.YES_NO_OPTION);
- if (i != JOptionPane.YES_OPTION) {
- return;
- }
- int score = examService.over();
- JOptionPane
- .showMessageDialog(examFrame, "Your Score:" + score);
- examFrame.dispose();
- menuFrame.setVisible(true);
- }
- //add check func
- /**
- * gain score
- * show score
- */
- void check() {
- try {
- int score = examService.checkScore();
- JOptionPane.showMessageDialog(menuFrame,"Your Score:"+score);
- }catch (Exception e){
- JOptionPane.showMessageDialog(menuFrame,e.getMessage());
- }
- }
- void waring() {
- String string = examService.getTestRule();
- JOptionPane.showMessageDialog(menuFrame,string);
- }
- /*添加next方法
- * 想办法得到一个ExamInfo(和之前的ExamInfo一样)
- * 想办法得到一个QuestionInfo(必须是下一个考题)
- * 调用examFrame.updateView(QuestionInfo q)更新界面
- * 重载
- * */
- }
复制代码
- package com.tarena.elts.test;
- import com.tarena.elts.entitiv.EntityContext;
- import com.tarena.elts.entitiv.ExamInfo;
- import com.tarena.elts.service.ExamService;
- import com.tarena.elts.service.ExamServiceImpl;
- import com.tarena.elts.ui.*;
- import com.tarena.elts.util.Config;
- /**
- * Created by EnderSnow on 2016/7/9.
- * Time:12:41
- * ${DESCRIPTION}
- * ${FILE_NAME}
- */
- public class testExam {
- public static void main(String[] args) {
- //some list object
- WelcomeFrame welcomeFrame = new WelcomeFrame();
- welcomeFrame.setVisible(true);
- }
- }
复制代码
- package com.tarena.elts.service;
- import com.tarena.elts.entitiv.*;
- import java.util.List;
- /**
- * Created by EnderSnow on 2016/7/8.
- * Time:9:24
- * ${DESCRIPTION} 登录的抽象功能,业务模型
- * ${FILE_NAME}
- */
- public interface ExamService {
- /*user login function ,finish this function and login*/
- User Login(int id, String pwd) throws IDorPWDException;
- void setEntityContext(EntityContext entityContext);
- //添加开始考试的方法 ExamInfo start()
- ExamInfo start();
- /*
- 添加获得考题信息的方法 getQuestionInfo(int index)
- */
- public QuestionInfo getQuestionInfo(int index);
- void setExamInfo(ExamInfo examInfo);
- int next(int countIndex, List<Integer> userAnswers);
- int back(int countIndex, List<Integer> optionStatus);
- int over();
- int checkScore();
- String getTestRule();
- }
复制代码
- package com.tarena.elts.service;
- import com.tarena.elts.entitiv.*;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.Random;
- /**
- * Created by EnderSnow on 2016/7/8.
- * Time:14:22
- * ${DESCRIPTION 业务逻辑层的实现类
- * ${FILE_NAME}
- */
- public class ExamServiceImpl implements ExamService {
- /*add one date control's EntityContext,using to call itself function to gain date*/
- private EntityContext entityContext;
- private User user;
- private ExamInfo examInfo;
- /* public void setExamInfo(ExamInfo examInfo) {
- this.examInfo = examInfo;
- }*/
- public void setUser(User user) {
- this.user = user;
- }
- public void setEntityContext(EntityContext entityContext) {
- this.entityContext = entityContext;
- }
- private String testrule = new String();
- //judge login success of failed
- public User Login(int id, String pwd) throws IDorPWDException {
- //1.according ID return User object
- User userById = entityContext.getUserById(id);
- //2.if there no ID ,return message that there no user
- if (userById == null) {
- throw new IDorPWDException("uesr is not exists");
- }
- //3.if there is ID ,judge the Password,if match ,execute next step
- //create paper,
- if (userById.getPwd().equals(pwd)) {
- setUser(userById);
- testrule = entityContext.getTestRule().toString();
- return userById;
- }
- //4.if match password failed,throw IDorPWDException
- throw new IDorPWDException("your password is wrong ,please check again!");
- }
- //重写ExamService接口的start方法,
- /*
- 创建考卷,调用createPaper,
- 创建ExamInfo对象,给各个ExamInfo赋值
- 科目:java 时间:10 总分:100 题量:10 考生:登录用户(在该类的login()方法中去找
- 返回ExamInfo对象,
- */
- @Override
- public ExamInfo start() {
- if (isFinished){
- throw new RuntimeException("already Exam,");
- }
- setPaper();
- createPaper(entityContext.getQuestionCount());
- examInfo.setTestUser(user);
- return examInfo;
- }
- public ArrayList<QuestionInfo> getPapers() {
- return papers;
- }
- private ArrayList<QuestionInfo> papers = new ArrayList<>();
- /**
- * 重写getQuestionInfo(int index)
- * 返回一道考题
- */
- @Override
- public QuestionInfo getQuestionInfo(int index) {
- return papers.get(index);
- }
- @Override
- public void setExamInfo(ExamInfo examInfo) {
- this.examInfo = examInfo;
- }
- @Override
- public int next(int index, List<Integer> userAnswers) {
- if (index >= examInfo.getQuestionCount() - 1) {
- index += 0;
- } else {
- QuestionInfo questionInfo = papers.get(index);
- questionInfo.setAnswers(userAnswers);
- index++;
- //System.out.println("index-2"+papers.get(index).getAnswers());
- }
- /* System.out.println("useranswes");
- for(int i = 0 ; i < index;i ++){
- System.out.println(papers.get(i).getAnswers());
- }*/
- return index;
- }
- @Override
- public int back(int countIndex, List<Integer> optionStatus) {
- if (countIndex <= 0) {
- countIndex += 0;
- } else {
- QuestionInfo questionInfo = papers.get(countIndex);
- questionInfo.setAnswers(optionStatus);
- countIndex--;
- }
- return countIndex;
- }
- /**
- * 添加一个私有的创建考卷功能方法createPaper(int numbers)
- * 根据参数随机获取entityContext里的考题集合,来自数据管理层的题,参数代表题量
- * 创建对应的QuestionInfo对象,(添加题号 考题 分数 )
- * 吧一个个的QuestionInfo对象手机起来,做为考卷的所有考题,
- */
- private void createPaper(int numbers) {
- int score = setScore();
- papers = new ArrayList<>();
- for (int t = 0; t < numbers; t++) {
- QuestionInfo questionInfo = new QuestionInfo();
- Random r = new Random();
- int index = r.nextInt(paper.size());
- Question q = paper.remove(index);
- //questionInfo = getQuestionInfo(t);
- questionInfo.setQuestionIndex(t + 1);
- questionInfo.setQuestionScore(score);
- questionInfo.setQuestion(q);
- papers.add(questionInfo);
- }
- }
- //创建一个包含所有考题的集合 List<Qusetion> paper
- private List<Question> paper;
- private void setPaper() {
- this.paper = entityContext.getQuestionList();
- }
- /**
- * 添加一个私有的setScore()
- * 首先的知道考卷的总分(ExamInfo),
- * 得知道考题的数量
- * 每道题的分数等于总分/题量,
- * 把每道题的分数分别给考题集合的每一道题,
- */
- private int setScore() {
- return examInfo.getTotalScore() / examInfo.getQuestionCount();
- }
- //exam over
- /**
- * calculate score
- * @return userScore
- */
- private int userScore;
- public int over() {
- int userScore = 0;
- for (QuestionInfo q: papers) {
- Question question = q.getQuestion();
- if (q.getAnswers().equals(question.getAnswers())){
- userScore+=q.getQuestionScore();
- }
- }
- this.isFinished =true;
- this.userScore = userScore;
- return userScore;
- }
- @Override
- public int checkScore() {
- if (!isFinished){
- throw new RuntimeException("you didn't Exam,please join it!");
- }
- return userScore;
- }
- @Override
- public String getTestRule() {
- return testrule;
- }
- /**
- * define a attribute judge whether test,default false
- */
- private boolean isFinished = false;
- }
复制代码
- package com.tarena.elts.service;
- /**
- * Created by EnderSnow on 2016/7/8.
- * Time:9:45
- * ${DESCRIPTION}
- * ${FILE_NAME}
- */
- public class IDorPWDException extends Exception {
- public IDorPWDException(){
- }
- public IDorPWDException(String message){
- super(message);
- }
- }
复制代码
- package com.tarena.elts.service;
- import com.tarena.elts.ui.ExamFrame;
- /**
- * Created by EnderSnow on 2016/7/10.
- * Time:15:29
- * ${DESCRIPTION}
- * ${FILE_NAME}
- */
- public class RemainTimer extends Thread {
- public void setTimer(long timer) {
- this.timeLimit = timer;
- }
- public long timer;
- private ExamFrame examFrame = new ExamFrame();
- private long timeLimit;
- public static void main(String[] args) {
- RemainTimer remainTimer = new RemainTimer();
- remainTimer.setTimer(10);
- remainTimer.run();
- }
- public void run() {
- timer = getTimeLimit();
- System.out.println(timer);
- long timeLimit = timer * 60;
- timer = timer * 60;
- String time;
- while (true) {
- long longtime = (timer - timeLimit) / 1000;
- time = String.format("%02d:%02d:%02d", (timer - longtime) / 3600,
- (timer - longtime) / 60, (timer - longtime) % 60);
- System.out.println(time);
- //examFrame.updateRemaingTime(time);
- try {
- Thread.sleep(1000);
- timer--;
- if (timer == 0) {
- break;
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- public long getTimeLimit() {
- return timeLimit;
- }
- /*
- public static void main(String[] args) {
- RemainTimer RemainTimer = new RemainTimer();
- RemainTimer.runTime(60);
- }
- public void runTime(int time){
- int i = 0 ;
- new Thread().start();
- while (i<time) {
- System.out.println(time - i);
- try {
- Thread.sleep(1000);
- i++;
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- if(i>=time){
- System.out.println("执行....");
- }
- */
- }
复制代码
- package com.tarena.elts.entitiv;
- import com.tarena.elts.util.Config;
- import java.io.BufferedReader;
- import java.io.FileInputStream;
- import java.io.InputStreamReader;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.List;
- /**
- * Created by EnderSnow on 2016/7/7.
- * Time:10:10
- * ${DESCRIPTION} /*数据管理 实体对象与数据库之间 值对象和项目的上下文关系
- * ${FILE_NAME}
- */
- public class EntityContext {
- //by key to find value, more easy to find user by ID
- private HashMap<Integer, User> userHashMap = new HashMap<>();
- Config config;
- public List<Question> getQuestion(int numbers) {
- ArrayList<Question> questions = new ArrayList<>();
- for (int i = 0; i < numbers; i++) {
- questions.add(questionList.get(i));
- }
- return questions;
- }
- public List<Question> getQuestionList() {
- return questionList;
- }
- //所有考题的示例集合,每一个元素就是每一个考题
- private List<Question> questionList = new ArrayList<>();
- public EntityContext(Config config) {
- this.config = config;
- loadUser(config.getString("UserFile"));
- loadQuestions(config.getString("QuestionFile"));
- loadTestRule(config.getString("TestRule"));
- }
- public StringBuffer getTestRule() {
- return stringBuffer;
- }
- private StringBuffer stringBuffer = new StringBuffer();
- private void loadTestRule(String filename){
- try {
- BufferedReader in = new BufferedReader(
- new InputStreamReader(
- new FileInputStream(filename), "utf-8"));
- String line;
- while ((line = in.readLine()) != null) {//till can't read date anymore
- //analyze line to transform User
- line = line.trim();//delete the blackSpace
- stringBuffer.append(line).append("n");
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * load user from date file
- * 1.find relative file by file name
- * 2.create the fileInputStream(input to system)
- * 3.read the row date
- * 4.Analyze the date
- * 5.create User through analyze result
- * 6.add User to Users
- */
- /*load User*/
- private void loadUser(String filename) {
- //in is according filename to creating the inputStream
- try {
- BufferedReader in = new BufferedReader(
- new InputStreamReader(
- new FileInputStream(filename), "utf-8"));
- String line;
- while ((line = in.readLine()) != null) {//till can't read date anymore
- //analyze line to transform User
- line = line.trim();//delete the blackSpace
- User user = parseUser(line);
- //give users to Usered
- userHashMap.put(user.getId(), user);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private User parseUser(String line) {
- //create User
- String[] strings = line.split(":");
- User user = new User();
- user.setId(Integer.parseInt(strings[0]));
- user.setName(strings[1]);
- user.setPwd(strings[2]);
- user.setPhone(strings[3]);
- user.setEmail(strings[4]);
- return user;
- }
- /**
- * load user from date file
- * 1.find relative file by file name
- * 2.create the fileInputStream(input to system)
- * 3.read the row date
- * 4.Analyze the date
- * 5.create question through analyze result
- * 6.add question to questionsList
- */
- private void loadQuestions(String filename) {
- try {
- BufferedReader in = new BufferedReader(
- new InputStreamReader(
- new FileInputStream(filename), "utf-8"));
- String line;
- while ((line = in.readLine()) != null) {
- if (line.startsWith("#") || line.equals(" ")) {
- continue;
- }
- //analyze date transform to questionList
- Question question = parseQuestion(line, in);
- //add result to questionList
- questionList.add(question);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- private Question parseQuestion(String line, BufferedReader in) throws Exception {
- //analyze the first row date to correct answer, level
- //1,(@多个字符=),2,(,多个字符=)
- //the result is {,2/3,5};
- Question question = new Question();
- String[] split = line.split("[@,][a-z]+=");
- //correct answer
- String[] answers = split[1].split("/");
- List<Integer> answersList = new ArrayList<>();
- for (String answer : answers) {
- answersList.add(Integer.parseInt(answer));
- }
- //title
- String title = in.readLine();
- //options
- List<String> optionals = new ArrayList<>();
- for (int i = 0; i < 4; i++) {
- optionals.add(in.readLine());
- }
- question.setAnswers(answersList);
- question.setOptions(optionals);
- question.setLevel(Integer.parseInt(split[2]));
- question.setTitle(title);
- return question;
- }
- //according ID return User
- public User getUserById(int id) {
- return userHashMap.get(id);
- }
- //gain ExamInfo attribute
- public String getExamTitle() {
- return config.getString("ExamTitle");
- }
- public int getTotalScore() {
- return config.getInt("TotalScore");
- }
- public int getTimeLimit() {
- return config.getInt("TimeLimit");
- }
- public int getQuestionCount() {
- return config.getInt("QuestionCount");
- }
- }
复制代码
- package com.tarena.elts.entitiv;
- /**
- * Created by EnderSnow on 2016/7/9.
- * Time:9:21
- * ${DESCRIPTION}封装考试的信息,包含考试科目,时间,题量,总分,考生
- * ${FILE_NAME}
- */
- public class ExamInfo {
- private String subject;// testing subject
- private int timeLimit;//testing time
- private int questionCount;//count of question
- private int totalScore;
- private User testUser;
- public ExamInfo(){
- }
- public int getTotalScore() {
- return totalScore;
- }
- public void setTotalScore(int totalScore) {
- this.totalScore = totalScore;
- }
- public int getQuestionCount() {
- return questionCount;
- }
- public void setQuestionCount(int questionCount) {
- this.questionCount = questionCount;
- }
- public User getTestUser() {
- return testUser;
- }
- public void setTestUser(User testUser) {
- this.testUser = testUser;
- }
- public int getTimeLimit() {
- return timeLimit;
- }
- public void setTimeLimit(int timeLimit) {
- this.timeLimit = timeLimit;
- }
- public String getSubject() {
- return subject;
- }
- public void setSubject(String subject) {
- this.subject = subject;
- }
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append("name:").append(testUser.getName());
- sb.append(" ID:").append(testUser.getId());
- sb.append(" Exam Subject:").append(subject);
- sb.append(" Exam Limit:").append(timeLimit);
- sb.append(" TotalScore:").append(totalScore);
- sb.append(" count of question:").append(questionCount);
- return sb.toString();
- }
- }
复制代码
- package com.tarena.elts.entitiv;
- import java.util.ArrayList;
- import java.util.List;
- /**
- * Created by EnderSnow on 2016/7/9.
- * Time:9:36
- * ${DESCRIPTION} 封装考题信息
- * 试卷中的题号
- * 每道题的分数
- * 考题(包含题干和选项)
- * 答题区
- * ${FILE_NAME}
- */
- public class QuestionInfo {
- private int questionIndex;
- private int questionScore;
- private Question question;
- private List<Integer> answers = new ArrayList<>();
- public QuestionInfo(){
- }
- public QuestionInfo(int questionIndex,Question question){
- this.questionIndex = questionIndex;
- this.question = question;
- }
- public Question getQuestion() {
- return question;
- }
- public void setQuestion(Question question) {
- this.question = question;
- }
- public int getQuestionScore() {
- return questionScore;
- }
- public void setQuestionScore(int questionScore) {
- this.questionScore = questionScore;
- }
- public int getQuestionIndex() {
- return questionIndex;
- }
- public void setQuestionIndex(int questionIndex) {
- this.questionIndex = questionIndex;
- }
- public List<Integer> getAnswers() {
- return answers;
- }
- public void setAnswers(List<Integer> answers) {
- this.answers = answers;
- }
- @Override
- public String toString() {
- return questionIndex+".("+questionScore+")"+question.toString();
- }
- }
复制代码
- package com.tarena.elts.entitiv;
- /**
- * Created by EnderSnow on 2016/7/7.
- * Time:9:02
- * ${DESCRIPTION}用户的实体类
- * ${FILE_NAME}
- */
- public class User {
- private int id;
- private String name;
- private String pwd;
- private String phone;
- private String email;
- public User(String name, int id, String pwd) {
- this.name = name;
- this.id = id;
- this.pwd = pwd;
- }
- @Override
- public boolean equals(Object o) {
- if (this == o) return true;
- if (o == null || getClass() != o.getClass()) return false;
- User user = (User) o;
- if (id != user.id) return false;
- return name != null ? name.equals(user.name) : user.name == null;
- }
- @Override
- public int hashCode() {
- int result = id;
- result = 31 * result + (name != null ? name.hashCode() : 0);
- return result;
- }
- public User() {
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getEmail() {
- return email;
- }
- public void setEmail(String email) {
- this.email = email;
- }
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getPhone() {
- return phone;
- }
- public void set
|