在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

考试系统

2016-7-29 15:47| 发布者: zhangjf| 查看: 717| 评论: 0

摘要: 本代码来自川师java实训,包结构在截图里面,resource里面是放的所有的图片,然后包截图里面有一个text的文件夹是放的property和那三个txt文件的,PS:有什么不懂得可以私我~ ...
本代码来自川师java实训,包结构在截图里面,resource里面是放的所有的图片,然后包截图里面有一个text的文件夹是放的property和那三个txt文件的,PS:有什么不懂得可以私我~
  1. package com.tarena.elts.util;
  2. import java.io.FileInputStream;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import java.io.InputStreamReader;
  6. import java.util.Properties;
  7. /**
  8. * Created by EnderSnow on 2016/7/7.
  9. * Time:10:14
  10. * ${DESCRIPTION}
  11. * ${FILE_NAME}
  12. */
  13. public class Config {
  14. private Properties table = new Properties();
  15. /* 给table赋值*/
  16. public Config(String filename) {
  17. try {
  18. table.load(new InputStreamReader(new FileInputStream(filename),"utf-8"));
  19. } catch (FileNotFoundException e) {
  20. System.out.println("can't find you properties file");//load thrown
  21. } catch (IOException e) {
  22. e.printStackTrace();//fileInputStream thrown
  23. }
  24. }
  25. public int getInt(String key) {//get the value of int
  26. return Integer.parseInt(table.getProperty(key));
  27. }
  28. public double getDouble(String key) {//get the value of double
  29. return Double.parseDouble(table.getProperty(key));
  30. }
  31. public String getString(String key) {//get the value of String
  32. return table.getProperty(key);
  33. }
  34. }
复制代码
  1. package com.tarena.elts.ui;
  2. import com.tarena.elts.entitiv.EntityContext;
  3. import com.tarena.elts.entitiv.ExamInfo;
  4. import com.tarena.elts.service.ExamService;
  5. import com.tarena.elts.service.ExamServiceImpl;
  6. import com.tarena.elts.util.Config;
  7. import javax.swing.*;
  8. import java.awt.*;
  9. import java.awt.event.MouseAdapter;
  10. import java.awt.event.MouseEvent;
  11. /**
  12. * Created by EnderSnow on 2016/7/6.
  13. * Time:9:20
  14. * ${DESCRIPTION}
  15. * ${FILE_NAME}
  16. */
  17. public class WelcomeFrame extends JFrame {
  18. public WelcomeFrame() {
  19. init();
  20. this.setVisible(true);
  21. }
  22. public void showLoginFrame() {
  23. Config config = new Config("text/client.properties");
  24. EntityContext entityContext = new EntityContext(config);
  25. LoginFrame loginFrame = new LoginFrame();
  26. MenuFrame menuFrame = new MenuFrame();
  27. ExamFrame examFrame = new ExamFrame();
  28. ClientContext clientContext = new ClientContext();
  29. ExamService examService = new ExamServiceImpl();
  30. examService.setEntityContext(entityContext);
  31. //科目:java 时间:10 总分:100 题量:10 考生:登录用户(在该类的login()方法中去找
  32. ExamInfo examInfo = new ExamInfo();
  33. examInfo.setSubject(entityContext.getExamTitle());
  34. examInfo.setQuestionCount(entityContext.getQuestionCount());
  35. examInfo.setTotalScore(entityContext.getTotalScore());
  36. examInfo.setTimeLimit(entityContext.getTimeLimit());
  37. examService.setExamInfo(examInfo);
  38. //inject attribute to object
  39. clientContext.setExamFrame(examFrame);
  40. loginFrame.setClientContext(clientContext);
  41. menuFrame.setClientContext(clientContext);
  42. examFrame.setClientContext(clientContext);
  43. clientContext.setLoginFrame(loginFrame);
  44. clientContext.setMenuFrame(menuFrame);
  45. clientContext.setExamService(examService);
  46. clientContext.setExamFrame(examFrame);
  47. clientContext.setExamInfo(examInfo);
  48. clientContext.show();
  49. }
  50. private void init() {
  51. this.setSize(993, 643);
  52. this.setLocationRelativeTo(null);
  53. this.setUndecorated(true);//delete the border
  54. this.setContentPane(createContenPane());
  55. addMouseListener(new MouseAdapter() {
  56. public void mousePressed(MouseEvent e) {
  57. setVisible(false);
  58. dispose();
  59. showLoginFrame();
  60. }
  61. });
  62. final int pause = 2000;
  63. /**
  64. * Swing线程在同一时刻仅能被一个线程所访问。一般来说,这个线程是事件派发线程(event-dispatching thread)。
  65. * 如果需要从事件处理(event-handling)或绘制代码以外的地方访问UI,
  66. * 那么可以使用SwingUtilities类的invokeLater()或invokeAndWait()方法。
  67. */
  68. // 关闭欢迎屏幕的线程
  69. final Runnable closerRunner = () -> {
  70. setVisible(false);
  71. dispose();
  72. showLoginFrame();
  73. };
  74. // 等待关闭欢迎屏幕的线程
  75. Runnable waitRunner = () -> {
  76. try {
  77. // 当显示了waitTime后,尝试关闭欢迎屏幕
  78. Thread.sleep(pause);
  79. SwingUtilities.invokeAndWait(closerRunner);
  80. // SwingUtilities.invokeLater(closerRunner);
  81. } catch (Exception e) {
  82. e.printStackTrace();
  83. }
  84. };
  85. setVisible(true);
  86. // 启动等待关闭欢迎屏幕的线程
  87. Thread splashThread = new Thread(waitRunner, "SplashThread");
  88. splashThread.start();
  89. }
  90. private Container createContenPane() {
  91. JPanel mainPanel = new JPanel();
  92. mainPanel.add(BorderLayout.CENTER, new JLabel(new ImageIcon("resource/welcome.png")));
  93. return mainPanel;
  94. }
  95. }
复制代码
  1. package com.tarena.elts.ui;
  2. import javax.swing.*;
  3. import javax.swing.border.Border;
  4. import java.awt.*;
  5. import java.awt.event.WindowAdapter;
  6. import java.awt.event.WindowEvent;
  7. /**
  8. * Created by EnderSnow on 2016/7/6.
  9. * Time:9:20
  10. * ${DESCRIPTION} menu frame
  11. * ${FILE_NAME}
  12. */
  13. public class MenuFrame extends JFrame {
  14. private JLabel informationLabel;
  15. public MenuFrame() {
  16. init();
  17. }
  18. private ClientContext clientContext;
  19. public void setClientContext(ClientContext clientContext) {
  20. this.clientContext = clientContext;
  21. }
  22. /**
  23. * frame init
  24. */
  25. private void init() {
  26. this.setTitle("Ender E-Learning Test System");
  27. this.setSize(880, 583);
  28. this.setLocationRelativeTo(null);//siting the frame in center
  29. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  30. this.setContentPane(createContentPanel());
  31. this.addWindowListener(new WindowAdapter() {
  32. @Override
  33. public void windowClosing(WindowEvent e) {
  34. clientContext.exit(MenuFrame.this);
  35. }
  36. });
  37. }
  38. /**
  39. * create the main content pane
  40. *
  41. * @return mainJPanel
  42. */
  43. private Container createContentPanel() {
  44. JPanel mainJPanel = new JPanel();
  45. mainJPanel.setLayout(new BorderLayout());
  46. mainJPanel.add(BorderLayout.NORTH, createTitleImagePanel());
  47. mainJPanel.add(BorderLayout.CENTER, createBtnImagePanel());
  48. mainJPanel.add(BorderLayout.SOUTH, createNoticePanel());
  49. return mainJPanel;
  50. }
  51. /**
  52. * create image title area
  53. *
  54. * @return ImageLabel
  55. */
  56. private Component createTitleImagePanel() {
  57. return new JLabel(new ImageIcon("resource/title2.png"));
  58. }
  59. private Component createBtnImagePanel() {
  60. JPanel btnPanel = new JPanel();
  61. btnPanel.setLayout(new BorderLayout());
  62. btnPanel.add(BorderLayout.NORTH, createInfoLabel());
  63. btnPanel.add(BorderLayout.CENTER, createBtnPanel());
  64. return btnPanel;
  65. }
  66. private Component createBtnPanel() {
  67. JPanel buttonPanel = new JPanel();
  68. buttonPanel.setLayout(new GridLayout(1, 4, 5, 5));
  69. JButton startBtn = createImageButton("resource/start.png", "Start Exam");
  70. JButton checkBtn = createImageButton("resource/score.png", "CheckScore");
  71. JButton waringBtn = createImageButton("resource/rule.png", "Notice Advice");
  72. JButton exitBtn = createImageButton("resource/exit.png", "Exit System");
  73. buttonPanel.add(startBtn);
  74. buttonPanel.add(checkBtn);
  75. buttonPanel.add(waringBtn);
  76. buttonPanel.add(exitBtn);
  77. //给开始考试按钮添加事件,该事件触发后调用ClientContext的start()
  78. startBtn.addActionListener(e -> clientContext.start());
  79. checkBtn.addActionListener(e -> clientContext.check());
  80. waringBtn.addActionListener(e -> clientContext.waring());
  81. exitBtn.addActionListener(e -> clientContext.exit(MenuFrame.this));
  82. return buttonPanel;
  83. }
  84. /**
  85. * create Info label
  86. *
  87. * @return informationLabel
  88. */
  89. private Component createInfoLabel() {
  90. informationLabel = new JLabel();
  91. informationLabel.setText("welcome to you,");
  92. informationLabel.setHorizontalAlignment(JLabel.CENTER);
  93. return informationLabel;
  94. }
  95. //update menu info label
  96. void updateInfo(String username) {
  97. informationLabel.setText("welcome to you," + username);
  98. }
  99. /**
  100. * create noticePanel
  101. *
  102. * @return NoticeJlabel
  103. */
  104. private Component createNoticePanel() {
  105. return new JLabel("all Rights Reserved-infringement", JLabel.RIGHT);
  106. }
  107. private JButton createImageButton(String iconPath, String msg) {
  108. ImageIcon icon = new ImageIcon(iconPath);
  109. JButton button = new JButton(msg, icon);
  110. Border b1 = BorderFactory.createLineBorder(Color.orange, 2);
  111. Border b2 = BorderFactory.createEmptyBorder(15, 5, 15, 5);
  112. button.setBorder(BorderFactory.createCompoundBorder(b1, b2));
  113. //将文本垂直方向底部对齐
  114. button.setVerticalTextPosition(JButton.BOTTOM);
  115. //将文本水平方向居中对齐
  116. button.setHorizontalTextPosition(JButton.CENTER);
  117. button.setOpaque(false);
  118. // button.setBorderPainted(false);
  119. return button;
  120. }
  121. /*add attribute of ClientContext,for this class calling control function调用控制器方法*/
  122. }
复制代码
  1. package com.tarena.elts.ui;
  2. import javax.swing.*;
  3. import javax.swing.border.EmptyBorder;
  4. import java.awt.*;
  5. import java.awt.event.WindowAdapter;
  6. import java.awt.event.WindowEvent;
  7. /**
  8. * Created by EnderSnow on 2016/7/6.
  9. * Time:9:20
  10. * ${DESCRIPTION} Login Frame
  11. * ${FILE_NAME}
  12. */
  13. public class LoginFrame extends JFrame {
  14. /*add property*/
  15. private ClientContext clientContext;
  16. private JTextField idTextFiled;
  17. private JPasswordField passwordField;
  18. private JLabel noticeLabel;
  19. private JPanel idPwdPanel;
  20. public LoginFrame() {
  21. init();
  22. }
  23. /**
  24. * initialize main frame
  25. */
  26. private void init() {
  27. this.setResizable(false);
  28. this.setTitle("Login");
  29. this.setSize(900, 590);
  30. this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
  31. this.setLocationRelativeTo(null);
  32. this.setContentPane(createContentPane());
  33. this.addWindowListener(new WindowAdapter() {
  34. @Override
  35. public void windowClosing(WindowEvent e) {
  36. clientContext.exit(LoginFrame.this);
  37. }
  38. });
  39. }
  40. /**
  41. * create mainPanel logic
  42. */
  43. private Container createContentPane() {
  44. JPanel mainPanel = new JPanel() {
  45. private static final long serialVersionUID = 1L;
  46. @Override
  47. protected void paintComponent(Graphics g) {
  48. super.paintComponent(g);
  49. g.drawImage(new ImageIcon(
  50. "resource/login.png").getImage(), 0,
  51. 0, getWidth(), getHeight(), null);
  52. }
  53. };
  54. mainPanel.setBorder(new EmptyBorder(10, 10, 10, 10));
  55. mainPanel.setLayout(new BorderLayout());
  56. mainPanel.add(BorderLayout.NORTH, new JLabel("LoginSystem", JLabel.CENTER));
  57. mainPanel.add(BorderLayout.CENTER, createCenterPane());
  58. mainPanel.add(BorderLayout.SOUTH, createBtnPane());
  59. mainPanel.setOpaque(false);
  60. return mainPanel;
  61. }
  62. /**
  63. * create south button area
  64. *
  65. * @return BtnPanel
  66. */
  67. private Component createBtnPane() {
  68. JPanel btnPanel = new JPanel(new FlowLayout()) {
  69. private static final long serialVersionUID = 1L;
  70. @Override
  71. protected void paintComponent(Graphics g) {
  72. super.paintComponent(g);
  73. g.drawImage(new ImageIcon(
  74. "resource/button.png").getImage(), 0,
  75. 0, getWidth(), getHeight(), null);
  76. }
  77. };
  78. JButton loginBtn = new JButton("Login");
  79. JButton cancelBtn = new JButton("Cancel");
  80. JButton noButton = new JButton();
  81. noButton.setBorderPainted(false);
  82. noButton.setContentAreaFilled(false);
  83. btnPanel.add(loginBtn);
  84. btnPanel.add(noButton);
  85. btnPanel.add(cancelBtn);
  86. loginBtn.addActionListener(e -> clientContext.Login());
  87. loginBtn.setOpaque(false);
  88. loginBtn.setBackground(Color.gray);
  89. loginBtn.setContentAreaFilled(false);
  90. loginBtn.setFont(new Font("微软雅黑", Font.BOLD, 12));
  91. loginBtn.setForeground(Color.YELLOW);
  92. cancelBtn.addActionListener(e -> clientContext.exit(LoginFrame.this));
  93. cancelBtn.setOpaque(false);
  94. cancelBtn.setBackground(Color.gray);
  95. cancelBtn.setContentAreaFilled(false);
  96. cancelBtn.setFont(new Font("微软雅黑", Font.BOLD, 12));
  97. cancelBtn.setForeground(Color.YELLOW);
  98. btnPanel.setOpaque(false);
  99. //loginBtn.setBounds();
  100. return btnPanel;
  101. }
  102. /**
  103. * create center ID and PWD area
  104. *
  105. * @return CenterPanel
  106. */
  107. private Component createCenterPane() {
  108. JPanel centerPanel = new JPanel(new BorderLayout());
  109. centerPanel.add(BorderLayout.CENTER, createFiledPane());
  110. centerPanel.add(BorderLayout.SOUTH, createNoticePane());
  111. centerPanel.setOpaque(false);
  112. return centerPanel;
  113. }
  114. /**
  115. * create notice label
  116. *
  117. * @return jLabel
  118. */
  119. private Component createNoticePane() {
  120. noticeLabel = new JLabel();
  121. noticeLabel.setText("try login?");
  122. noticeLabel.setHorizontalAlignment(JLabel.CENTER);
  123. return noticeLabel;
  124. }
  125. /**
  126. * create id and pwd Panel
  127. *
  128. * @return IdPwdPanel
  129. */
  130. private Component createFiledPane() {
  131. //idPwdPanel = new JPanel(new GridLayout(2, 1, 0, 15));
  132. idPwdPanel = new JPanel();
  133. idPwdPanel.setLayout(null);
  134. idPwdPanel.add(createIdPane());
  135. idPwdPanel.setOpaque(false);
  136. idPwdPanel.add(createPwdPane());
  137. idPwdPanel.setAlignmentY(JPanel.CENTER_ALIGNMENT);
  138. // idPwdPanel.setBounds(410,330,320,45);
  139. return idPwdPanel;
  140. }
  141. /**
  142. * create ID input panel;
  143. *
  144. * @return IDPanel
  145. */
  146. private Component createIdPane() {
  147. JPanel idPanel = new JPanel(new BorderLayout());
  148. //idPanel.setForeground(Color.red);
  149. JLabel idLabel = new JLabel();
  150. idLabel.setOpaque(false);
  151. JTextField idTextFiled = new JTextField();
  152. this.idTextFiled = idTextFiled;
  153. idPanel.add(BorderLayout.WEST, idLabel);
  154. idPanel.add(BorderLayout.CENTER, idTextFiled);
  155. idPanel.setOpaque(false);
  156. idTextFiled.setOpaque(false);
  157. idPanel.setBounds(413, 210, 143, 25);
  158. return idPanel;
  159. }
  160. /*gain idField text*/
  161. String getUserId() {
  162. return idTextFiled.getText();
  163. }
  164. /**
  165. * create Password input panel
  166. *
  167. * @return pwdPanel
  168. */
  169. private Component createPwdPane() {
  170. JPanel pwdPanel = new JPanel(new BorderLayout());
  171. JLabel pwdLabel = new JLabel();
  172. pwdLabel.setOpaque(false);
  173. JPasswordField passwordField = new JPasswordField();
  174. this.passwordField = passwordField;
  175. pwdPanel.add(BorderLayout.WEST, pwdLabel);
  176. pwdPanel.add(BorderLayout.CENTER, passwordField);
  177. pwdPanel.setOpaque(false);
  178. passwordField.setOpaque(false);
  179. pwdPanel.setBounds(413, 245, 143, 25);
  180. return pwdPanel;
  181. }
  182. //gain user Password
  183. String getUserPwd() {
  184. char temp[] = passwordField.getPassword();
  185. return new String(temp);
  186. }
  187. /*add set methed to property for outside calling,to attribute for object injection,keep your project only one target,*/
  188. public void setClientContext(ClientContext clientContext) {
  189. this.clientContext = clientContext;
  190. }
  191. //show wrong message
  192. void showMessage(String message) {
  193. noticeLabel.setForeground(Color.RED);
  194. noticeLabel.setText(message);//noticeLabel 's setText methed
  195. }
  196. }
复制代码
  1. package com.tarena.elts.ui;
  2. import com.tarena.elts.entitiv.ExamInfo;
  3. import com.tarena.elts.entitiv.QuestionInfo;
  4. import javax.swing.*;
  5. import javax.swing.border.EmptyBorder;
  6. import javax.swing.border.TitledBorder;
  7. import java.awt.*;
  8. import java.awt.event.WindowAdapter;
  9. import java.awt.event.WindowEvent;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. /**
  13. * Created by EnderSnow on 2016/7/6.
  14. * Time:9:19
  15. * ${DESCRIPTION} Exam frame
  16. * ${FILE_NAME}
  17. */
  18. public class ExamFrame extends JFrame {
  19. public ExamFrame() {
  20. init();
  21. }
  22. /**
  23. * initialise ExamFrame
  24. */
  25. private void init() {
  26. this.setTitle("Ender Technology Online Exam");
  27. this.setSize(800, 700);
  28. this.setLocationRelativeTo(null);
  29. this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  30. this.setContentPane(createContentPanel());
  31. this.addWindowListener(new WindowAdapter() {
  32. @Override
  33. public void windowClosing(WindowEvent e) {
  34. clientContext.submit();
  35. }
  36. });
  37. }
  38. /**
  39. * create ContentPanel
  40. *
  41. * @return mainPanel
  42. */
  43. private Container createContentPanel() {
  44. JPanel mainPanel = new JPanel();
  45. mainPanel.setLayout(new BorderLayout());
  46. mainPanel.add(BorderLayout.NORTH, createtitleImagePanel());
  47. mainPanel.add(BorderLayout.CENTER, createQuestionFiled());
  48. mainPanel.add(BorderLayout.SOUTH, createToolPanel());
  49. return mainPanel;
  50. }
  51. /**
  52. * create title Image
  53. *
  54. * @return Jlabel
  55. */
  56. private Component createtitleImagePanel() {
  57. // imageLabel.setSize(new Dimension(800,370));
  58. return new JLabel(new ImageIcon("resource/exam_title2.png"));
  59. }
  60. /**
  61. * create question Area
  62. *
  63. * @return QuestionPanel
  64. */
  65. private Component createQuestionFiled() {
  66. JPanel QuestionPanel = new JPanel();
  67. QuestionPanel.setLayout(new BorderLayout());
  68. QuestionPanel.add(BorderLayout.NORTH, createInfoLabel());
  69. QuestionPanel.add(BorderLayout.CENTER, createQuestionPanel());
  70. QuestionPanel.add(BorderLayout.SOUTH, createOptionPanel());
  71. return QuestionPanel;
  72. }
  73. /**
  74. * create center qustion field
  75. *
  76. * @return QuestionPanel
  77. */
  78. private JTextArea qusetionArea;
  79. private Component createQuestionPanel() {
  80. JScrollPane QuestionPanel = new JScrollPane();
  81. QuestionPanel.setBorder(new TitledBorder("problems-"));
  82. qusetionArea = new JTextArea(6, 15);
  83. qusetionArea.setBorder(new EmptyBorder(3, 3, 3, 3));
  84. qusetionArea.setLineWrap(true);//anto wrap line
  85. qusetionArea.setEditable(false);//set this area is uneditable
  86. QuestionPanel.getViewport().add(qusetionArea);
  87. return QuestionPanel;
  88. }
  89. /**
  90. * create chosenPanel
  91. *
  92. * @return chosenPanel
  93. */
  94. private Option a;
  95. private Option b;
  96. private Option c;
  97. private Option d;
  98. private Component createOptionPanel() {
  99. JPanel chosenPanel = new JPanel();
  100. // ButtonGroup buttonGroup = new ButtonGroup();
  101. a = new Option(0, "A");
  102. b = new Option(1, "B");
  103. c = new Option(2, "C");
  104. d = new Option(3, "D");
  105. chosenPanel.add(a);
  106. chosenPanel.add(b);
  107. chosenPanel.add(c);
  108. chosenPanel.add(d);
  109. //chosenPanel.add(select);
  110. return chosenPanel;
  111. }
  112. private JLabel infoLabel;
  113. /**
  114. * create personal Info Label
  115. *
  116. * @return infoLabel
  117. */
  118. private Component createInfoLabel() {
  119. infoLabel = new JLabel();
  120. infoLabel.setText("name:xxx id:0527 subject: java ExamTime: 60 min");
  121. infoLabel.setHorizontalAlignment(JLabel.CENTER);
  122. return infoLabel;
  123. }
  124. /**
  125. * create tool Panel
  126. *
  127. * @return toolBtnPanel
  128. */
  129. private Component createToolPanel() {
  130. JPanel toolBtnPanel = new JPanel() {
  131. private static final long serialVersionUID = 1L;
  132. @Override
  133. protected void paintComponent(Graphics g) {
  134. super.paintComponent(g);
  135. g.drawImage(new ImageIcon(
  136. "resource/button2.png").getImage(), 0,
  137. 0, getWidth(), getHeight(), null);
  138. }
  139. };
  140. toolBtnPanel.setLayout(new BorderLayout());
  141. toolBtnPanel.add(BorderLayout.WEST, createProLabel());
  142. toolBtnPanel.add(BorderLayout.CENTER, createToolBtn());
  143. toolBtnPanel.add(BorderLayout.EAST, createTimeLabel());
  144. return toolBtnPanel;
  145. }
  146. /**
  147. * create toolBtn area
  148. *
  149. * @return toolBtn
  150. */
  151. private Component createToolBtn() {
  152. JPanel toolBtn = new JPanel();
  153. toolBtn.setOpaque(false);
  154. toolBtn.setForeground(Color.cyan);
  155. JButton backBtn = new JButton("back");
  156. JButton nextBtn = new JButton("next");
  157. JButton submitBtn = new JButton("Submit");
  158. backBtn.setOpaque(false);
  159. nextBtn.setOpaque(false);
  160. submitBtn.setOpaque(false);
  161. toolBtn.add(backBtn);
  162. toolBtn.add(nextBtn);
  163. toolBtn.add(submitBtn);
  164. //给下一题按钮添加事件,此事件触发后调用控制器的next()
  165. nextBtn.addActionListener(e -> clientContext.next());
  166. backBtn.addActionListener(e -> clientContext.back());
  167. submitBtn.addActionListener(e -> clientContext.submit());
  168. return toolBtn;
  169. }
  170. List<Integer> getOptionStatus() {//to gain user's optionsList
  171. ArrayList<Integer> answersList = new ArrayList<>();
  172. if (a.isSelected()) {
  173. answersList.add(a.value);
  174. }
  175. if (b.isSelected()) {
  176. answersList.add(b.value);
  177. }
  178. if (c.isSelected()) {
  179. answersList.add(c.value);
  180. }
  181. if (d.isSelected()) {
  182. answersList.add(d.value);
  183. }
  184. //System.out.println(answersList);
  185. return answersList;
  186. }
  187. /**
  188. * create problem Notice label
  189. *
  190. * @return proLabel
  191. */
  192. private JLabel proLabel;
  193. private Component createProLabel() {
  194. JPanel proPanel = new JPanel(new FlowLayout());
  195. proPanel.setPreferredSize(new Dimension(150,10));
  196. proLabel = new JLabel();
  197. proLabel.setText("NO.x in Paper");
  198. proPanel.add(proLabel);
  199. proLabel.setHorizontalAlignment(JLabel.LEFT);
  200. proPanel.setOpaque(false);
  201. return proPanel;
  202. }
  203. /**
  204. * create leftTime notice label
  205. *
  206. * @return leftLabel
  207. */
  208. private JLabel leftLabel;
  209. private Component createTimeLabel() {
  210. JPanel timePanel = new JPanel(new FlowLayout());
  211. setPreferredSize(new Dimension(100,10));
  212. leftLabel = new JLabel();
  213. leftLabel.setText("Remaining Time:");
  214. leftLabel.setHorizontalAlignment(JLabel.RIGHT);
  215. timePanel.add(leftLabel);
  216. timePanel.setOpaque(false);
  217. return timePanel;
  218. }
  219. void updateRemaingTime(int time) {
  220. if (time == 0){
  221. clientContext.submit();
  222. clientContext.cancel();
  223. }
  224. String dateString = String.format("%02d:%02d:%02d", time / 3600,
  225. time / 60, time % 60);
  226. leftLabel.setText("Remaining Time:"+dateString);
  227. }
  228. /* 内部类 扩展API的多选框 有int类型的value参数,代表答案传给服务器*/
  229. private class Option extends JCheckBox {
  230. int value;
  231. Option(int value, String text) {
  232. super(text);//call super construction methed that carry one paremeter
  233. this.value = value;
  234. }
  235. }
  236. private void clearOptions() {
  237. a.setSelected(false);
  238. b.setSelected(false);
  239. c.setSelected(false);
  240. d.setSelected(false);
  241. }
  242. void updateView(ExamInfo start, QuestionInfo questionInfo) {
  243. clearOptions();
  244. infoLabel.setText(start.toString());
  245. qusetionArea.setText(questionInfo.toString());
  246. // System.out.println(questionInfo.getQuestionIndex());
  247. proLabel.setText("NO." + questionInfo.getQuestionIndex() + " in this paper");
  248. }
  249. /**
  250. * refactoring updateView
  251. * update questionInfo and optionStatus
  252. */
  253. void updateView(QuestionInfo questionInfo, List<Integer> answering) {
  254. clearOptions();
  255. qusetionArea.setText(questionInfo.toString());
  256. proLabel.setText("NO." + questionInfo.getQuestionIndex() + " in this paper");
  257. for (Integer i : answering) {
  258. switch (i) {
  259. case 0:
  260. a.setSelected(true);
  261. break;
  262. case 1:
  263. b.setSelected(true);
  264. break;
  265. case 2:
  266. c.setSelected(true);
  267. break;
  268. case 3:
  269. d.setSelected(true);
  270. break;
  271. }
  272. }
  273. }
  274. /**
  275. * 添加updateView(ExamInfo e,QuestionInfo q)
  276. * 把考试信息给该界面中的ExamArea(考题区面板)
  277. * 把QuestionInfo的信息给奔雷当中的QuestionArea
  278. * 把第几题给本类当中的左下角的proLabel
  279. */
  280. /*添加控制器属性,便于本类访问控制器方法*/
  281. private ClientContext clientContext;
  282. /*添加对象注入的set方法*/
  283. public void setClientContext(ClientContext clientContext) {
  284. this.clientContext = clientContext;
  285. }
  286. }
复制代码
  1. package com.tarena.elts.ui;
  2. import com.tarena.elts.entitiv.ExamInfo;
  3. import com.tarena.elts.entitiv.QuestionInfo;
  4. import com.tarena.elts.entitiv.User;
  5. import com.tarena.elts.service.ExamService;
  6. import com.tarena.elts.service.IDorPWDException;
  7. import javax.swing.*;
  8. import java.awt.*;
  9. import java.util.*;
  10. import java.util.Timer;
  11. ;
  12. /**
  13. * Created by EnderSnow on 2016/7/8.
  14. * Time:9:25
  15. * ${DESCRIPTION} the control between frame and model
  16. * ${FILE_NAME}
  17. */
  18. public class ClientContext {
  19. /**
  20. * login
  21. * 1.gain user ID and PWD
  22. * 2.call model login methed,finish user login
  23. * 3.according result,update frame,show user information
  24. * closing login frame,open menu frame,
  25. * 4.if login failed,show failed message
  26. */
  27. private LoginFrame loginframe;
  28. //登录界面对象的应用,达到控制器能够操作登录界面
  29. public void setLoginFrame(LoginFrame loginframe) {
  30. this.loginframe = loginframe;
  31. }
  32. private MenuFrame menuFrame;
  33. //菜单界面对象的应用,达到控制器能够操作菜单界面
  34. public void setMenuFrame(MenuFrame menuFrame) {
  35. this.menuFrame = menuFrame;
  36. }
  37. private ExamService examService;
  38. //增加业务模型实现的属性,达到控制器调用业务模型中的方法
  39. public void setExamService(ExamService examService) {
  40. this.examService = examService;
  41. }
  42. void Login() {
  43. try {
  44. String userId = loginframe.getUserId();//gain Id
  45. String userPwd = loginframe.getUserPwd();//gain password
  46. User user = examService.Login(Integer.parseInt(userId), userPwd);
  47. //update menu frame
  48. menuFrame.updateInfo(user.getName());
  49. loginframe.dispose();//closing login frame
  50. menuFrame.setVisible(true);//show menu frame
  51. } catch (IDorPWDException e) {
  52. //执行用户Id和PWD错误的逻辑
  53. loginframe.showMessage("login failed" + e.getMessage());
  54. e.printStackTrace();
  55. } catch (NumberFormatException e) {
  56. loginframe.showMessage("your id should be Integer");
  57. } catch (Exception e) {
  58. loginframe.showMessage("login failed" + e.getMessage());
  59. }
  60. }
  61. //frame show
  62. public void show() {
  63. loginframe.setVisible(true);
  64. }
  65. //close frame
  66. void exit(Component from) {
  67. int res = JOptionPane.showConfirmDialog(from, "are you sure to leave?", "please ensure", JOptionPane.YES_NO_OPTION);
  68. if (res == JOptionPane.YES_OPTION) {
  69. System.exit(0);
  70. }
  71. }
  72. //添加考试界面的属性
  73. private ExamFrame examFrame;
  74. //添加考试界面的set方法
  75. public void setExamFrame(ExamFrame examFrame) {
  76. this.examFrame = examFrame;
  77. }
  78. //定义开始考试的start方法
  79. //调用ExamService的start(),返回ExamInfo,包含考试信息,
  80. //调用ExamService的getQuestionInfo(0),获得一道考题,用于更新考试界面,
  81. //更新考试界面,调用考试界面的更新方法updateView(ExamInfo e,QuestionInfo q)
  82. //关闭菜单界面
  83. //显示考试界面
  84. private int countIndex = 0;
  85. private QuestionInfo questionInfo = new QuestionInfo();
  86. void start() {
  87. try {
  88. ExamInfo start = examService.start();
  89. questionInfo = examService.getQuestionInfo(countIndex);
  90. examFrame.updateView(start, questionInfo);
  91. menuFrame.setVisible(false);
  92. examFrame.setVisible(true);
  93. updateTime();
  94. } catch (Exception e) {
  95. JOptionPane.showMessageDialog(menuFrame,e.getMessage());
  96. }
  97. }
  98. private java.util.Timer timer;
  99. private void updateTime(){
  100. TimerTask timerTask = new TimerTask() {
  101. private int i = 0;
  102. @Override
  103. public void run() {
  104. examFrame.updateRemaingTime(examInfo.getTimeLimit()*60 -i );
  105. ++i;
  106. }
  107. };
  108. timer = new Timer();
  109. timer.schedule(timerTask,0,1000);
  110. }
  111. void cancel(){
  112. timer.cancel();
  113. System.out.println("已经关闭timer");
  114. }
  115. private ExamInfo examInfo = new ExamInfo();
  116. void next() {
  117. countIndex = examService.next(countIndex, examFrame.getOptionStatus());
  118. questionInfo = examService.getQuestionInfo(countIndex);
  119. examFrame.updateView(questionInfo, questionInfo.getAnswers());
  120. }
  121. void back() {
  122. countIndex = examService.back(countIndex, examFrame.getOptionStatus());
  123. questionInfo = examService.getQuestionInfo(countIndex);
  124. //System.out.println(questionInfo.getAnswers());
  125. examFrame.updateView(questionInfo, questionInfo.getAnswers());
  126. }
  127. public void setExamInfo(ExamInfo examInfo) {
  128. this.examInfo = examInfo;
  129. }
  130. void submit() {
  131. examService.next(countIndex, examFrame.getOptionStatus());
  132. int i = JOptionPane.showConfirmDialog(examFrame, "ensure to submit", "please ensure to submit?", JOptionPane.YES_NO_OPTION);
  133. if (i != JOptionPane.YES_OPTION) {
  134. return;
  135. }
  136. int score = examService.over();
  137. JOptionPane
  138. .showMessageDialog(examFrame, "Your Score:" + score);
  139. examFrame.dispose();
  140. menuFrame.setVisible(true);
  141. }
  142. //add check func
  143. /**
  144. * gain score
  145. * show score
  146. */
  147. void check() {
  148. try {
  149. int score = examService.checkScore();
  150. JOptionPane.showMessageDialog(menuFrame,"Your Score:"+score);
  151. }catch (Exception e){
  152. JOptionPane.showMessageDialog(menuFrame,e.getMessage());
  153. }
  154. }
  155. void waring() {
  156. String string = examService.getTestRule();
  157. JOptionPane.showMessageDialog(menuFrame,string);
  158. }
  159. /*添加next方法
  160. * 想办法得到一个ExamInfo(和之前的ExamInfo一样)
  161. * 想办法得到一个QuestionInfo(必须是下一个考题)
  162. * 调用examFrame.updateView(QuestionInfo q)更新界面
  163. * 重载
  164. * */
  165. }
复制代码
  1. package com.tarena.elts.test;
  2. import com.tarena.elts.entitiv.EntityContext;
  3. import com.tarena.elts.entitiv.ExamInfo;
  4. import com.tarena.elts.service.ExamService;
  5. import com.tarena.elts.service.ExamServiceImpl;
  6. import com.tarena.elts.ui.*;
  7. import com.tarena.elts.util.Config;
  8. /**
  9. * Created by EnderSnow on 2016/7/9.
  10. * Time:12:41
  11. * ${DESCRIPTION}
  12. * ${FILE_NAME}
  13. */
  14. public class testExam {
  15. public static void main(String[] args) {
  16. //some list object
  17. WelcomeFrame welcomeFrame = new WelcomeFrame();
  18. welcomeFrame.setVisible(true);
  19. }
  20. }
复制代码
  1. package com.tarena.elts.service;
  2. import com.tarena.elts.entitiv.*;
  3. import java.util.List;
  4. /**
  5. * Created by EnderSnow on 2016/7/8.
  6. * Time:9:24
  7. * ${DESCRIPTION} 登录的抽象功能,业务模型
  8. * ${FILE_NAME}
  9. */
  10. public interface ExamService {
  11. /*user login function ,finish this function and login*/
  12. User Login(int id, String pwd) throws IDorPWDException;
  13. void setEntityContext(EntityContext entityContext);
  14. //添加开始考试的方法 ExamInfo start()
  15. ExamInfo start();
  16. /*
  17. 添加获得考题信息的方法 getQuestionInfo(int index)
  18. */
  19. public QuestionInfo getQuestionInfo(int index);
  20. void setExamInfo(ExamInfo examInfo);
  21. int next(int countIndex, List<Integer> userAnswers);
  22. int back(int countIndex, List<Integer> optionStatus);
  23. int over();
  24. int checkScore();
  25. String getTestRule();
  26. }
复制代码
  1. package com.tarena.elts.service;
  2. import com.tarena.elts.entitiv.*;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import java.util.Random;
  6. /**
  7. * Created by EnderSnow on 2016/7/8.
  8. * Time:14:22
  9. * ${DESCRIPTION 业务逻辑层的实现类
  10. * ${FILE_NAME}
  11. */
  12. public class ExamServiceImpl implements ExamService {
  13. /*add one date control's EntityContext,using to call itself function to gain date*/
  14. private EntityContext entityContext;
  15. private User user;
  16. private ExamInfo examInfo;
  17. /* public void setExamInfo(ExamInfo examInfo) {
  18. this.examInfo = examInfo;
  19. }*/
  20. public void setUser(User user) {
  21. this.user = user;
  22. }
  23. public void setEntityContext(EntityContext entityContext) {
  24. this.entityContext = entityContext;
  25. }
  26. private String testrule = new String();
  27. //judge login success of failed
  28. public User Login(int id, String pwd) throws IDorPWDException {
  29. //1.according ID return User object
  30. User userById = entityContext.getUserById(id);
  31. //2.if there no ID ,return message that there no user
  32. if (userById == null) {
  33. throw new IDorPWDException("uesr is not exists");
  34. }
  35. //3.if there is ID ,judge the Password,if match ,execute next step
  36. //create paper,
  37. if (userById.getPwd().equals(pwd)) {
  38. setUser(userById);
  39. testrule = entityContext.getTestRule().toString();
  40. return userById;
  41. }
  42. //4.if match password failed,throw IDorPWDException
  43. throw new IDorPWDException("your password is wrong ,please check again!");
  44. }
  45. //重写ExamService接口的start方法,
  46. /*
  47. 创建考卷,调用createPaper,
  48. 创建ExamInfo对象,给各个ExamInfo赋值
  49. 科目:java 时间:10 总分:100 题量:10 考生:登录用户(在该类的login()方法中去找
  50. 返回ExamInfo对象,
  51. */
  52. @Override
  53. public ExamInfo start() {
  54. if (isFinished){
  55. throw new RuntimeException("already Exam,");
  56. }
  57. setPaper();
  58. createPaper(entityContext.getQuestionCount());
  59. examInfo.setTestUser(user);
  60. return examInfo;
  61. }
  62. public ArrayList<QuestionInfo> getPapers() {
  63. return papers;
  64. }
  65. private ArrayList<QuestionInfo> papers = new ArrayList<>();
  66. /**
  67. * 重写getQuestionInfo(int index)
  68. * 返回一道考题
  69. */
  70. @Override
  71. public QuestionInfo getQuestionInfo(int index) {
  72. return papers.get(index);
  73. }
  74. @Override
  75. public void setExamInfo(ExamInfo examInfo) {
  76. this.examInfo = examInfo;
  77. }
  78. @Override
  79. public int next(int index, List<Integer> userAnswers) {
  80. if (index >= examInfo.getQuestionCount() - 1) {
  81. index += 0;
  82. } else {
  83. QuestionInfo questionInfo = papers.get(index);
  84. questionInfo.setAnswers(userAnswers);
  85. index++;
  86. //System.out.println("index-2"+papers.get(index).getAnswers());
  87. }
  88. /* System.out.println("useranswes");
  89. for(int i = 0 ; i < index;i ++){
  90. System.out.println(papers.get(i).getAnswers());
  91. }*/
  92. return index;
  93. }
  94. @Override
  95. public int back(int countIndex, List<Integer> optionStatus) {
  96. if (countIndex <= 0) {
  97. countIndex += 0;
  98. } else {
  99. QuestionInfo questionInfo = papers.get(countIndex);
  100. questionInfo.setAnswers(optionStatus);
  101. countIndex--;
  102. }
  103. return countIndex;
  104. }
  105. /**
  106. * 添加一个私有的创建考卷功能方法createPaper(int numbers)
  107. * 根据参数随机获取entityContext里的考题集合,来自数据管理层的题,参数代表题量
  108. * 创建对应的QuestionInfo对象,(添加题号 考题 分数 )
  109. * 吧一个个的QuestionInfo对象手机起来,做为考卷的所有考题,
  110. */
  111. private void createPaper(int numbers) {
  112. int score = setScore();
  113. papers = new ArrayList<>();
  114. for (int t = 0; t < numbers; t++) {
  115. QuestionInfo questionInfo = new QuestionInfo();
  116. Random r = new Random();
  117. int index = r.nextInt(paper.size());
  118. Question q = paper.remove(index);
  119. //questionInfo = getQuestionInfo(t);
  120. questionInfo.setQuestionIndex(t + 1);
  121. questionInfo.setQuestionScore(score);
  122. questionInfo.setQuestion(q);
  123. papers.add(questionInfo);
  124. }
  125. }
  126. //创建一个包含所有考题的集合 List<Qusetion> paper
  127. private List<Question> paper;
  128. private void setPaper() {
  129. this.paper = entityContext.getQuestionList();
  130. }
  131. /**
  132. * 添加一个私有的setScore()
  133. * 首先的知道考卷的总分(ExamInfo),
  134. * 得知道考题的数量
  135. * 每道题的分数等于总分/题量,
  136. * 把每道题的分数分别给考题集合的每一道题,
  137. */
  138. private int setScore() {
  139. return examInfo.getTotalScore() / examInfo.getQuestionCount();
  140. }
  141. //exam over
  142. /**
  143. * calculate score
  144. * @return userScore
  145. */
  146. private int userScore;
  147. public int over() {
  148. int userScore = 0;
  149. for (QuestionInfo q: papers) {
  150. Question question = q.getQuestion();
  151. if (q.getAnswers().equals(question.getAnswers())){
  152. userScore+=q.getQuestionScore();
  153. }
  154. }
  155. this.isFinished =true;
  156. this.userScore = userScore;
  157. return userScore;
  158. }
  159. @Override
  160. public int checkScore() {
  161. if (!isFinished){
  162. throw new RuntimeException("you didn't Exam,please join it!");
  163. }
  164. return userScore;
  165. }
  166. @Override
  167. public String getTestRule() {
  168. return testrule;
  169. }
  170. /**
  171. * define a attribute judge whether test,default false
  172. */
  173. private boolean isFinished = false;
  174. }
复制代码
  1. package com.tarena.elts.service;
  2. /**
  3. * Created by EnderSnow on 2016/7/8.
  4. * Time:9:45
  5. * ${DESCRIPTION}
  6. * ${FILE_NAME}
  7. */
  8. public class IDorPWDException extends Exception {
  9. public IDorPWDException(){
  10. }
  11. public IDorPWDException(String message){
  12. super(message);
  13. }
  14. }
复制代码
  1. package com.tarena.elts.service;
  2. import com.tarena.elts.ui.ExamFrame;
  3. /**
  4. * Created by EnderSnow on 2016/7/10.
  5. * Time:15:29
  6. * ${DESCRIPTION}
  7. * ${FILE_NAME}
  8. */
  9. public class RemainTimer extends Thread {
  10. public void setTimer(long timer) {
  11. this.timeLimit = timer;
  12. }
  13. public long timer;
  14. private ExamFrame examFrame = new ExamFrame();
  15. private long timeLimit;
  16. public static void main(String[] args) {
  17. RemainTimer remainTimer = new RemainTimer();
  18. remainTimer.setTimer(10);
  19. remainTimer.run();
  20. }
  21. public void run() {
  22. timer = getTimeLimit();
  23. System.out.println(timer);
  24. long timeLimit = timer * 60;
  25. timer = timer * 60;
  26. String time;
  27. while (true) {
  28. long longtime = (timer - timeLimit) / 1000;
  29. time = String.format("%02d:%02d:%02d", (timer - longtime) / 3600,
  30. (timer - longtime) / 60, (timer - longtime) % 60);
  31. System.out.println(time);
  32. //examFrame.updateRemaingTime(time);
  33. try {
  34. Thread.sleep(1000);
  35. timer--;
  36. if (timer == 0) {
  37. break;
  38. }
  39. } catch (InterruptedException e) {
  40. e.printStackTrace();
  41. }
  42. }
  43. }
  44. public long getTimeLimit() {
  45. return timeLimit;
  46. }
  47. /*
  48. public static void main(String[] args) {
  49. RemainTimer RemainTimer = new RemainTimer();
  50. RemainTimer.runTime(60);
  51. }
  52. public void runTime(int time){
  53. int i = 0 ;
  54. new Thread().start();
  55. while (i<time) {
  56. System.out.println(time - i);
  57. try {
  58. Thread.sleep(1000);
  59. i++;
  60. } catch (InterruptedException e) {
  61. // TODO Auto-generated catch block
  62. e.printStackTrace();
  63. }
  64. }
  65. if(i>=time){
  66. System.out.println("执行....");
  67. }
  68. */
  69. }
复制代码
  1. package com.tarena.elts.entitiv;
  2. import com.tarena.elts.util.Config;
  3. import java.io.BufferedReader;
  4. import java.io.FileInputStream;
  5. import java.io.InputStreamReader;
  6. import java.util.ArrayList;
  7. import java.util.HashMap;
  8. import java.util.List;
  9. /**
  10. * Created by EnderSnow on 2016/7/7.
  11. * Time:10:10
  12. * ${DESCRIPTION} /*数据管理 实体对象与数据库之间 值对象和项目的上下文关系
  13. * ${FILE_NAME}
  14. */
  15. public class EntityContext {
  16. //by key to find value, more easy to find user by ID
  17. private HashMap<Integer, User> userHashMap = new HashMap<>();
  18. Config config;
  19. public List<Question> getQuestion(int numbers) {
  20. ArrayList<Question> questions = new ArrayList<>();
  21. for (int i = 0; i < numbers; i++) {
  22. questions.add(questionList.get(i));
  23. }
  24. return questions;
  25. }
  26. public List<Question> getQuestionList() {
  27. return questionList;
  28. }
  29. //所有考题的示例集合,每一个元素就是每一个考题
  30. private List<Question> questionList = new ArrayList<>();
  31. public EntityContext(Config config) {
  32. this.config = config;
  33. loadUser(config.getString("UserFile"));
  34. loadQuestions(config.getString("QuestionFile"));
  35. loadTestRule(config.getString("TestRule"));
  36. }
  37. public StringBuffer getTestRule() {
  38. return stringBuffer;
  39. }
  40. private StringBuffer stringBuffer = new StringBuffer();
  41. private void loadTestRule(String filename){
  42. try {
  43. BufferedReader in = new BufferedReader(
  44. new InputStreamReader(
  45. new FileInputStream(filename), "utf-8"));
  46. String line;
  47. while ((line = in.readLine()) != null) {//till can't read date anymore
  48. //analyze line to transform User
  49. line = line.trim();//delete the blackSpace
  50. stringBuffer.append(line).append("n");
  51. }
  52. } catch (Exception e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. /**
  57. * load user from date file
  58. * 1.find relative file by file name
  59. * 2.create the fileInputStream(input to system)
  60. * 3.read the row date
  61. * 4.Analyze the date
  62. * 5.create User through analyze result
  63. * 6.add User to Users
  64. */
  65. /*load User*/
  66. private void loadUser(String filename) {
  67. //in is according filename to creating the inputStream
  68. try {
  69. BufferedReader in = new BufferedReader(
  70. new InputStreamReader(
  71. new FileInputStream(filename), "utf-8"));
  72. String line;
  73. while ((line = in.readLine()) != null) {//till can't read date anymore
  74. //analyze line to transform User
  75. line = line.trim();//delete the blackSpace
  76. User user = parseUser(line);
  77. //give users to Usered
  78. userHashMap.put(user.getId(), user);
  79. }
  80. } catch (Exception e) {
  81. e.printStackTrace();
  82. }
  83. }
  84. private User parseUser(String line) {
  85. //create User
  86. String[] strings = line.split(":");
  87. User user = new User();
  88. user.setId(Integer.parseInt(strings[0]));
  89. user.setName(strings[1]);
  90. user.setPwd(strings[2]);
  91. user.setPhone(strings[3]);
  92. user.setEmail(strings[4]);
  93. return user;
  94. }
  95. /**
  96. * load user from date file
  97. * 1.find relative file by file name
  98. * 2.create the fileInputStream(input to system)
  99. * 3.read the row date
  100. * 4.Analyze the date
  101. * 5.create question through analyze result
  102. * 6.add question to questionsList
  103. */
  104. private void loadQuestions(String filename) {
  105. try {
  106. BufferedReader in = new BufferedReader(
  107. new InputStreamReader(
  108. new FileInputStream(filename), "utf-8"));
  109. String line;
  110. while ((line = in.readLine()) != null) {
  111. if (line.startsWith("#") || line.equals(" ")) {
  112. continue;
  113. }
  114. //analyze date transform to questionList
  115. Question question = parseQuestion(line, in);
  116. //add result to questionList
  117. questionList.add(question);
  118. }
  119. } catch (Exception e) {
  120. e.printStackTrace();
  121. }
  122. }
  123. private Question parseQuestion(String line, BufferedReader in) throws Exception {
  124. //analyze the first row date to correct answer, level
  125. //1,(@多个字符=),2,(,多个字符=)
  126. //the result is {,2/3,5};
  127. Question question = new Question();
  128. String[] split = line.split("[@,][a-z]+=");
  129. //correct answer
  130. String[] answers = split[1].split("/");
  131. List<Integer> answersList = new ArrayList<>();
  132. for (String answer : answers) {
  133. answersList.add(Integer.parseInt(answer));
  134. }
  135. //title
  136. String title = in.readLine();
  137. //options
  138. List<String> optionals = new ArrayList<>();
  139. for (int i = 0; i < 4; i++) {
  140. optionals.add(in.readLine());
  141. }
  142. question.setAnswers(answersList);
  143. question.setOptions(optionals);
  144. question.setLevel(Integer.parseInt(split[2]));
  145. question.setTitle(title);
  146. return question;
  147. }
  148. //according ID return User
  149. public User getUserById(int id) {
  150. return userHashMap.get(id);
  151. }
  152. //gain ExamInfo attribute
  153. public String getExamTitle() {
  154. return config.getString("ExamTitle");
  155. }
  156. public int getTotalScore() {
  157. return config.getInt("TotalScore");
  158. }
  159. public int getTimeLimit() {
  160. return config.getInt("TimeLimit");
  161. }
  162. public int getQuestionCount() {
  163. return config.getInt("QuestionCount");
  164. }
  165. }
复制代码
  1. package com.tarena.elts.entitiv;
  2. /**
  3. * Created by EnderSnow on 2016/7/9.
  4. * Time:9:21
  5. * ${DESCRIPTION}封装考试的信息,包含考试科目,时间,题量,总分,考生
  6. * ${FILE_NAME}
  7. */
  8. public class ExamInfo {
  9. private String subject;// testing subject
  10. private int timeLimit;//testing time
  11. private int questionCount;//count of question
  12. private int totalScore;
  13. private User testUser;
  14. public ExamInfo(){
  15. }
  16. public int getTotalScore() {
  17. return totalScore;
  18. }
  19. public void setTotalScore(int totalScore) {
  20. this.totalScore = totalScore;
  21. }
  22. public int getQuestionCount() {
  23. return questionCount;
  24. }
  25. public void setQuestionCount(int questionCount) {
  26. this.questionCount = questionCount;
  27. }
  28. public User getTestUser() {
  29. return testUser;
  30. }
  31. public void setTestUser(User testUser) {
  32. this.testUser = testUser;
  33. }
  34. public int getTimeLimit() {
  35. return timeLimit;
  36. }
  37. public void setTimeLimit(int timeLimit) {
  38. this.timeLimit = timeLimit;
  39. }
  40. public String getSubject() {
  41. return subject;
  42. }
  43. public void setSubject(String subject) {
  44. this.subject = subject;
  45. }
  46. @Override
  47. public String toString() {
  48. StringBuilder sb = new StringBuilder();
  49. sb.append("name:").append(testUser.getName());
  50. sb.append(" ID:").append(testUser.getId());
  51. sb.append(" Exam Subject:").append(subject);
  52. sb.append(" Exam Limit:").append(timeLimit);
  53. sb.append(" TotalScore:").append(totalScore);
  54. sb.append(" count of question:").append(questionCount);
  55. return sb.toString();
  56. }
  57. }
复制代码
  1. package com.tarena.elts.entitiv;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. /**
  5. * Created by EnderSnow on 2016/7/7.
  6. * Time:9:18
  7. * ${DESCRIPTION} 考题类
  8. * 对象是题库中的每一个考题
  9. * ${FILE_NAME}
  10. */
  11. public class Question {
  12. public static final int LEVEL1 = 1;//qusetion level
  13. public static final int LEVEL2 = 2;
  14. public static final int LEVEL3 = 3;
  15. public static final int LEVEL4 = 4;
  16. public static final int LEVEL5 = 5;
  17. public static final int LEVEL6 = 6;
  18. public static final int LEVEL7 = 7;
  19. public static final int LEVEL8 = 8;
  20. public static final int LEVEL9 = 9;
  21. public static final int LEVEL0 = 10;
  22. public static final int SINGEL_SELECT = 0;//singel select
  23. public static final int MULT_SELECT = 1;//mult select
  24. private String title;//qusetion
  25. private int level;//the difficult
  26. private int quesId;//question id
  27. private int type;//one or more answers
  28. private List<Integer> answers = new ArrayList<Integer>();//correct answers
  29. private List<String> options = new ArrayList<>();//questions options
  30. public Question(List<String> options, String title, int type) {
  31. this.options = options;
  32. this.title = title;
  33. this.type = type;
  34. }
  35. public Question() {
  36. }
  37. public String getTitle() {
  38. return title;
  39. }
  40. public void setTitle(String title) {
  41. this.title = title;
  42. }
  43. public int getQuesId() {
  44. return quesId;
  45. }
  46. public void setQuesId(int quesId) {
  47. this.quesId = quesId;
  48. }
  49. public List<Integer> getAnswers() {
  50. return answers;
  51. }
  52. public void setAnswers(List<Integer> answers) {
  53. this.answers = answers;
  54. }
  55. public List<String> getOptions() {
  56. return options;
  57. }
  58. public void setOptions(List<String> options) {
  59. this.options = options;
  60. }
  61. public int getLevel() {
  62. return level;
  63. }
  64. public void setLevel(int level) {
  65. this.level = level;
  66. }
  67. public int getType() {
  68. return type;
  69. }
  70. public void setType(int type) {
  71. this.type = type;
  72. }
  73. @Override
  74. public boolean equals(Object o) {
  75. if (this == o) return true;
  76. if (o == null || getClass() != o.getClass()) return false;
  77. Question question = (Question) o;
  78. return title != null ? title.equals(question.title) : question.title == null
  79. && (answers != null ? answers.equals(question.answers) : question.answers == null
  80. && (options != null ? options.equals(question.options) : question.options == null));
  81. }
  82. @Override
  83. public int hashCode() {
  84. int result = title != null ? title.hashCode() : 0;
  85. result = 31 * result + (answers != null ? answers.hashCode() : 0);
  86. result = 31 * result + (options != null ? options.hashCode() : 0);
  87. return result;
  88. }
  89. @Override
  90. public String toString() {
  91. //question options answers
  92. StringBuilder sb = new StringBuilder();
  93. sb.append(title);
  94. sb.append(" level:").append(level);
  95. //title
  96. sb.append("n");
  97. //options
  98. for (int i = 0; i < options.size(); i++) {
  99. sb.append(((char) (i + 'A'))).
  100. append(".").
  101. append(options.get(i)).
  102. append("n");
  103. }
  104. //answers
  105. /*sb.append("correct answers:");
  106. for (Integer answer : answers) {
  107. sb.append((char) (answer + 'A')).
  108. append(" ");
  109. }*/
  110. sb.append("n");
  111. return sb.toString();
  112. }
  113. }
复制代码
  1. package com.tarena.elts.entitiv;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. /**
  5. * Created by EnderSnow on 2016/7/9.
  6. * Time:9:36
  7. * ${DESCRIPTION} 封装考题信息
  8. * 试卷中的题号
  9. * 每道题的分数
  10. * 考题(包含题干和选项)
  11. * 答题区
  12. * ${FILE_NAME}
  13. */
  14. public class QuestionInfo {
  15. private int questionIndex;
  16. private int questionScore;
  17. private Question question;
  18. private List<Integer> answers = new ArrayList<>();
  19. public QuestionInfo(){
  20. }
  21. public QuestionInfo(int questionIndex,Question question){
  22. this.questionIndex = questionIndex;
  23. this.question = question;
  24. }
  25. public Question getQuestion() {
  26. return question;
  27. }
  28. public void setQuestion(Question question) {
  29. this.question = question;
  30. }
  31. public int getQuestionScore() {
  32. return questionScore;
  33. }
  34. public void setQuestionScore(int questionScore) {
  35. this.questionScore = questionScore;
  36. }
  37. public int getQuestionIndex() {
  38. return questionIndex;
  39. }
  40. public void setQuestionIndex(int questionIndex) {
  41. this.questionIndex = questionIndex;
  42. }
  43. public List<Integer> getAnswers() {
  44. return answers;
  45. }
  46. public void setAnswers(List<Integer> answers) {
  47. this.answers = answers;
  48. }
  49. @Override
  50. public String toString() {
  51. return questionIndex+".("+questionScore+")"+question.toString();
  52. }
  53. }
复制代码
  1. package com.tarena.elts.entitiv;
  2. /**
  3. * Created by EnderSnow on 2016/7/7.
  4. * Time:9:02
  5. * ${DESCRIPTION}用户的实体类
  6. * ${FILE_NAME}
  7. */
  8. public class User {
  9. private int id;
  10. private String name;
  11. private String pwd;
  12. private String phone;
  13. private String email;
  14. public User(String name, int id, String pwd) {
  15. this.name = name;
  16. this.id = id;
  17. this.pwd = pwd;
  18. }
  19. @Override
  20. public boolean equals(Object o) {
  21. if (this == o) return true;
  22. if (o == null || getClass() != o.getClass()) return false;
  23. User user = (User) o;
  24. if (id != user.id) return false;
  25. return name != null ? name.equals(user.name) : user.name == null;
  26. }
  27. @Override
  28. public int hashCode() {
  29. int result = id;
  30. result = 31 * result + (name != null ? name.hashCode() : 0);
  31. return result;
  32. }
  33. public User() {
  34. }
  35. public String getName() {
  36. return name;
  37. }
  38. public void setName(String name) {
  39. this.name = name;
  40. }
  41. public String getEmail() {
  42. return email;
  43. }
  44. public void setEmail(String email) {
  45. this.email = email;
  46. }
  47. public int getId() {
  48. return id;
  49. }
  50. public void setId(int id) {
  51. this.id = id;
  52. }
  53. public String getPhone() {
  54. return phone;
  55. }
  56. public void set

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-6 12:12

Copyright 2015-2025 djqfx

返回顶部