TimePanel.java 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. package ui.view;
  2. import ui.controller.Control;
  3. import ui.controller.SingletonControl;
  4. import ui.model.Model;
  5. import utility.ImageImport;
  6. import javax.swing.*;
  7. import javax.swing.event.ChangeEvent;
  8. import javax.swing.event.ChangeListener;
  9. import javax.swing.plaf.basic.BasicSliderUI;
  10. import java.awt.*;
  11. import java.awt.event.*;
  12. import java.util.Hashtable;
  13. import java.util.concurrent.Executors;
  14. import java.util.concurrent.Future;
  15. import java.util.concurrent.ScheduledFuture;
  16. import java.util.concurrent.ScheduledThreadPoolExecutor;
  17. import java.util.concurrent.TimeUnit;
  18. /**
  19. * This Class represents a Panel where the User can start and stop the
  20. * Simulation. He Can also reset the Simulation and click through every
  21. * Iteration.
  22. *
  23. * @author Gruppe14
  24. */
  25. public class TimePanel extends JPanel implements ActionListener{
  26. private static final long serialVersionUID = 1L;
  27. private static final int MAX_ITERATIONS=100000;
  28. /*
  29. * variable for calculating the performance
  30. */
  31. //private long performanceTime;
  32. final JButton playBtn = new JButton();
  33. final JButton timeResetBtn = new JButton();
  34. final JButton timeForwardBtn = new JButton();
  35. final JButton timeBackwardBtn = new JButton();
  36. JTextField iterationsField;
  37. final JLabel iterationsLabel=new JLabel("Iterations:" , SwingConstants.CENTER);
  38. JLabel hint = new JLabel("Invalid", SwingConstants.RIGHT);
  39. private final JPanel btnAndSpeedPanel = new JPanel();
  40. private final JPanel speedPanel = new JPanel();
  41. private final JPanel timeBtnPanel = new JPanel();
  42. private final JPanel iterationsPanel=new JPanel();
  43. private final JPanel timePanel=new JPanel();
  44. private ScheduledFuture<?> futureTask;
  45. //private LabelHint iterationsLblHint;
  46. JSlider timeSlider = new JSlider() {
  47. /**
  48. *
  49. */
  50. private static final long serialVersionUID = 1L;
  51. {
  52. // Make the slider jump to mouse position on left click
  53. MouseListener[] listeners = getMouseListeners();
  54. for (MouseListener l : listeners)
  55. removeMouseListener(l); // remove UI-installed TrackListener
  56. final BasicSliderUI ui = (BasicSliderUI) getUI();
  57. BasicSliderUI.TrackListener tl = ui.new TrackListener() {
  58. // this is where we jump to absolute value of click
  59. @Override
  60. public void mouseClicked(MouseEvent e) {
  61. Point p = e.getPoint();
  62. int value = ui.valueForXPosition(p.x);
  63. setValue(value);
  64. }
  65. // disable check that will invoke scrollDueToClickInTrack
  66. @Override
  67. public boolean shouldScroll(int dir) {
  68. return false;
  69. }
  70. };
  71. addMouseListener(tl);
  72. }
  73. };
  74. //private Model model;
  75. private Control controller;
  76. private int dragResetIteration = 0;
  77. private JLabel simSpeedLabel = new JLabel("Speed:");
  78. private JSlider speedSlider = new JSlider();
  79. private Timer timer;
  80. private boolean running = false;
  81. private GUI parentGUI;
  82. /**
  83. * Constructor.
  84. *
  85. * @param mod
  86. * the Model
  87. * @param cont
  88. * the Controller
  89. */
  90. public TimePanel(GUI parent, Control cont) {
  91. super();
  92. this.controller = cont;
  93. this.parentGUI=parent;
  94. // One Iteration
  95. timer = new Timer(0, new ActionListener() {//TODO: Merge all these damned listeners.
  96. @Override
  97. public void actionPerformed(ActionEvent ae) {
  98. timeSlider.setValue(timeSlider.getValue() + 1);
  99. System.out.println(timeSlider.getValue());
  100. int test = timeSlider.getValue();
  101. controller.setCurIteration(timeSlider.getValue());
  102. timer.setDelay(cont.getModel().getTimerSpeed());
  103. if (timeSlider.getValue() >= cont.getModel().getIterations() - 1) {
  104. /*/calc and print performance
  105. performanceTime = System.nanoTime()-performanceTime;
  106. System.out.println(performanceTime/1000000000 + " Sekunden "
  107. + (performanceTime%1000000000)/1000000 + " Millisekunden "
  108. + (performanceTime%1000000)/1000 + " Mikrosekunden ");
  109. //*/
  110. running = false;
  111. playBtn.setIcon(new ImageIcon(ImageImport.loadImage("/Button_Images/play.png", 30, 30)));
  112. timer.stop();
  113. }
  114. }
  115. });
  116. // Time Slider. Panels and Buttons
  117. this.setLayout(new BorderLayout(0, 0));
  118. this.setBorder(null);
  119. // Slider
  120. timeSlider.setPaintTicks(true);
  121. timeSlider.setPaintLabels(true);
  122. timeSlider.setMajorTickSpacing((int)Math.ceil(((double)cont.getModel().getIterations())/20));
  123. timeSlider.setMinorTickSpacing((int)Math.ceil(((double)cont.getModel().getIterations())/100));
  124. timeSlider.setToolTipText(Languages.getLanguage()[93]);
  125. timeSlider.setMaximum(cont.getModel().getIterations() - 1);
  126. timeSlider.setValue(0);
  127. timeSlider.addChangeListener(changeEvent -> controller.setCurIteration(timeSlider.getValue()));
  128. timeSlider.addMouseListener(new MouseAdapter() {
  129. @Override
  130. public void mousePressed(MouseEvent e) {
  131. dragResetIteration = cont.getModel().getCurIteration();
  132. }
  133. });
  134. timeSlider.addMouseMotionListener(new MouseAdapter() {
  135. @Override
  136. public void mouseDragged(MouseEvent e) {
  137. if (dragResetIteration != cont.getModel().getCurIteration()) {
  138. controller.setIsSimRunning(true);
  139. if (running) {
  140. playBtn.doClick();
  141. }
  142. }
  143. }
  144. });
  145. // Panel
  146. timeBtnPanel.setBorder(null);
  147. timeBtnPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
  148. // Buttons
  149. playBtn.setToolTipText(Languages.getLanguage()[89]);
  150. playBtn.setContentAreaFilled(false);
  151. playBtn.setBorderPainted(false);
  152. playBtn.setBorder(null);
  153. playBtn.setIcon(new ImageIcon(ImageImport.loadImage("/Button_Images/play.png",30,30)));
  154. playBtn.addActionListener(new ActionListener() {
  155. @Override
  156. public void actionPerformed(ActionEvent e) {
  157. if(cont.getModel().getCurIteration()==cont.getModel().getIterations()-1)timeSlider.setValue(timeSlider.getMinimum());
  158. running = !running;
  159. controller.setIsSimRunning(running);
  160. if (running) {
  161. timer.setDelay(cont.getModel().getTimerSpeed());
  162. /*
  163. * start the Performance Test
  164. * /
  165. performanceTime = System.nanoTime();
  166. timeSlider.setValue(0);
  167. timer.setDelay(0);
  168. speedSlider.setValue(10);
  169. timeSlider.setValue(0);
  170. //*/
  171. timer.start();
  172. playBtn.setIcon(new ImageIcon(ImageImport.loadImage("/Button_Images/pause.png", 30, 30)));
  173. } else {
  174. timer.stop();
  175. playBtn.setIcon(new ImageIcon(ImageImport.loadImage("/Button_Images/play.png", 30, 30)));
  176. }
  177. }
  178. });
  179. timeResetBtn.setToolTipText(Languages.getLanguage()[90]);
  180. timeResetBtn.setContentAreaFilled(false);
  181. timeResetBtn.setBorder(null);
  182. timeResetBtn.setIcon(new ImageIcon(ImageImport.loadImage("/Button_Images/reset.png", 30, 30)));
  183. timeResetBtn.addActionListener(new ActionListener() {
  184. public void actionPerformed(ActionEvent ae) {
  185. timeSlider.setValue(timeSlider.getMinimum());
  186. controller.setCurIteration(timeSlider.getValue());
  187. // controller.calculateStateForCurrentTimeStep();
  188. controller.resetSimulation();
  189. if (running) {
  190. playBtn.doClick();
  191. }
  192. }
  193. });
  194. timeForwardBtn.setToolTipText(Languages.getLanguage()[91]);
  195. timeForwardBtn.setContentAreaFilled(false);
  196. timeForwardBtn.setBorder(null);
  197. timeForwardBtn.setIcon(new ImageIcon(ImageImport.loadImage("/Button_Images/forward.png",30,30)));
  198. timeForwardBtn.addActionListener(new ActionListener() {
  199. public void actionPerformed(ActionEvent ae) {
  200. if (!cont.getModel().getIsSimRunning()) {
  201. controller.setIsSimRunning(true);
  202. }
  203. timeSlider.setValue(timeSlider.getValue() + 1);
  204. controller.setCurIteration(timeSlider.getValue());
  205. }
  206. });
  207. timeBackwardBtn.setToolTipText(Languages.getLanguage()[92]);
  208. timeBackwardBtn.setBorder(null);
  209. timeBackwardBtn.setIcon(new ImageIcon(ImageImport.loadImage("/Button_Images/backward.png", 30,30)));
  210. timeBackwardBtn.addActionListener(new ActionListener() {
  211. public void actionPerformed(ActionEvent ae) {
  212. timeSlider.setValue(timeSlider.getValue() - 1);
  213. controller.setCurIteration(timeSlider.getValue());
  214. }
  215. });
  216. timeBtnPanel.add(playBtn);
  217. timeBtnPanel.add(Box.createRigidArea(new Dimension(10, 0)));
  218. timeBtnPanel.add(timeResetBtn);
  219. timeBtnPanel.add(Box.createRigidArea(new Dimension(10, 0)));
  220. timeBtnPanel.add(timeForwardBtn);
  221. // Speed Panel
  222. speedPanel.add(simSpeedLabel);
  223. speedPanel.add(speedSlider);
  224. speedSlider.setPaintTicks(true);
  225. speedSlider.setPaintLabels(true);
  226. speedSlider.setMaximum(6);
  227. speedSlider.setMinimum(0);
  228. speedSlider.setValue(1);
  229. speedSlider.setPaintLabels(true);
  230. Hashtable<Integer, JLabel> table = new Hashtable<Integer, JLabel>();
  231. table.put (0, new JLabel("1x"));
  232. table.put (1, new JLabel("2x"));
  233. table.put (2, new JLabel("4x"));
  234. table.put (3, new JLabel("8x"));
  235. table.put (4, new JLabel("16x"));
  236. table.put (5, new JLabel("32x"));
  237. table.put (6, new JLabel("64x"));
  238. speedSlider.setLabelTable(table);
  239. speedSlider.addChangeListener(new ChangeListener() {
  240. @Override
  241. public void stateChanged(ChangeEvent e) {
  242. /**
  243. * Shifting Powers of two:
  244. * e.g. 1<<0 -> 1 step per Second
  245. * 1<<3 -> 8 steps per Second
  246. * and so on,
  247. */
  248. int calculationsPerSecond = 1 << speedSlider.getValue();
  249. controller.setTimerSpeed(1024 >> speedSlider.getValue());
  250. speedSlider.setToolTipText("Speed: " + calculationsPerSecond + " Calculations per Second.");
  251. }
  252. });
  253. speedSlider.setToolTipText("Change the Number of Calculations per Secons");
  254. // Buttons and Speed Panel
  255. btnAndSpeedPanel.setLayout(new BorderLayout(0, 0));
  256. btnAndSpeedPanel.setBorder(null);
  257. btnAndSpeedPanel.add(timeBtnPanel, BorderLayout.NORTH);
  258. btnAndSpeedPanel.add(speedPanel, BorderLayout.CENTER);
  259. iterationsPanel.setLayout(new GridBagLayout());
  260. GridBagConstraints c = new GridBagConstraints();
  261. c.anchor = GridBagConstraints.CENTER;
  262. c.fill = GridBagConstraints.HORIZONTAL;
  263. c.gridx = 0;
  264. c.gridy = 0;
  265. iterationsPanel.add(iterationsLabel, c);
  266. //iterationsLblHint=new LabelHint(iterationsLabel);
  267. hint.setForeground(Color.red);
  268. hint.setText(" ");
  269. iterationsField=new JTextField(6);//Considering hundreds of thousands in an extreme case
  270. iterationsField.setText(""+cont.getModel().getIterations());
  271. iterationsField.setToolTipText("0-" + MAX_ITERATIONS );
  272. iterationsField.addActionListener(this);
  273. ScheduledThreadPoolExecutor s = new ScheduledThreadPoolExecutor(1);
  274. iterationsField.addCaretListener((e)->
  275. {
  276. try{
  277. int a=Integer.parseInt(iterationsField.getText());
  278. iterationsField.setBackground(Color.WHITE);//red stings
  279. //this.actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "like Enter")); that is lagging
  280. if(futureTask != null){
  281. futureTask.cancel(true);
  282. }
  283. futureTask = s.schedule((Runnable)() -> updateIterationsInput(), 1, TimeUnit.SECONDS);
  284. hint.setText(" ");
  285. }catch(NumberFormatException n){
  286. iterationsField.setBackground(GUI.PALE_RED);//red stings
  287. hint.setText("Invalid");
  288. }
  289. }
  290. );
  291. iterationsField.addFocusListener((interfaces.FocusListener)(e) ->{
  292. //FocusLost is not defined in interface have to be defined here
  293. updateIterationsInput();
  294. });
  295. c.gridy = 1;
  296. iterationsPanel.add(iterationsField, c);
  297. c.gridy = 2;
  298. iterationsPanel.add(hint, c);
  299. //iterationsPanel.add(new JLabel(), BorderLayout.SOUTH);
  300. timePanel.setLayout(new BorderLayout());;
  301. timePanel.add(iterationsPanel, BorderLayout.WEST);
  302. timePanel.add(timeSlider, BorderLayout.CENTER);
  303. this.add(btnAndSpeedPanel, BorderLayout.WEST);
  304. add(timePanel);
  305. //Disable Keys
  306. timeSlider.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0, false), "UP_ARROW");
  307. timeSlider.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0, false), "DOWN_ARROW");
  308. timeSlider.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0, false), "PAGE_DOWN");
  309. timeSlider.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0, false), "PAGE_UP");
  310. timeSlider.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0, false), "END");
  311. timeSlider.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0, false), "HOME");
  312. // Left arrow Key
  313. timeSlider.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0, false), "LEFT_ARROW");
  314. timeSlider.getActionMap().put("LEFT_ARROW", new AbstractAction() {
  315. private static final long serialVersionUID = 1L;
  316. @Override
  317. public void actionPerformed(ActionEvent e) {
  318. timeSlider.setValue(timeSlider.getValue() - 1);
  319. controller.resetSimulation();
  320. }
  321. });
  322. //Right arrow Key
  323. timeSlider.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0, false), "Right_ARROW");
  324. timeSlider.getActionMap().put("Right_ARROW", new AbstractAction() {
  325. private static final long serialVersionUID = 1L;
  326. @Override
  327. public void actionPerformed(ActionEvent e) {
  328. if (!cont.getModel().getIsSimRunning()) {
  329. controller.setIsSimRunning(true);
  330. }
  331. timeSlider.setValue(timeSlider.getValue() + 1);
  332. }
  333. });
  334. }
  335. /**
  336. * Returns the TimeSlider.
  337. *
  338. * @return the TimeSlider
  339. */
  340. public JSlider getTimeSlider() {
  341. return timeSlider;
  342. }
  343. @Override
  344. public void actionPerformed(ActionEvent arg0) {
  345. updateIterationsInput();
  346. }
  347. /**
  348. * Update the Text field and apply valid changes to update Iterations from to model.
  349. * <p>
  350. * Executed by user input.
  351. */
  352. private void updateIterationsInput() {
  353. try{
  354. int iterations=Integer.parseInt(iterationsField.getText());
  355. //iterationsLblHint.reset();
  356. boolean resetField=true;
  357. if(iterations<1)iterations=1;
  358. else if(iterations>MAX_ITERATIONS)iterations=MAX_ITERATIONS;
  359. else resetField=false;
  360. if(resetField)iterationsField.setText(""+iterations);
  361. controller.getModel().setIterations(Integer.parseInt(iterationsField.getText()));
  362. timeSlider.setMaximum(controller.getModel().getIterations()-1);
  363. timeSlider.setLabelTable(null);//Otherwise the ticks won't update
  364. timeSlider.setMajorTickSpacing((int)Math.ceil(((double)iterations)/20));
  365. timeSlider.setMinorTickSpacing((int)Math.ceil(((double)iterations)/100));//Even though the final mark can't actually be reached.
  366. parentGUI.updateIterations();//First one in the chain
  367. }catch(NumberFormatException e){}
  368. }
  369. }