Randomizer.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. package addOns;
  2. import java.awt.BorderLayout;
  3. import java.awt.Dimension;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.text.NumberFormat;
  8. import java.util.ArrayList;
  9. import java.util.Comparator;
  10. import java.util.HashMap;
  11. import java.util.Hashtable;
  12. import java.util.List;
  13. import java.util.stream.Collectors;
  14. import javax.swing.BorderFactory;
  15. import javax.swing.Box;
  16. import javax.swing.BoxLayout;
  17. import javax.swing.ImageIcon;
  18. import javax.swing.JButton;
  19. import javax.swing.JCheckBox;
  20. import javax.swing.JFileChooser;
  21. import javax.swing.JFormattedTextField;
  22. import javax.swing.JFrame;
  23. import javax.swing.JLabel;
  24. import javax.swing.JPanel;
  25. import javax.swing.JScrollPane;
  26. import javax.swing.JSlider;
  27. import javax.swing.JSplitPane;
  28. import javax.swing.filechooser.FileNameExtensionFilter;
  29. import javax.swing.text.NumberFormatter;
  30. import com.google.gson.Gson;
  31. import com.google.gson.JsonArray;
  32. import com.google.gson.JsonElement;
  33. import com.google.gson.JsonIOException;
  34. import com.google.gson.JsonParser;
  35. import com.google.gson.JsonSyntaxException;
  36. import addOns.Utility.HolonElementSketch;
  37. import addOns.Utility.RandomPriotity;
  38. import api.AddOn;
  39. import classes.AbstractCanvasObject;
  40. import classes.GroupNode;
  41. import classes.HolonElement;
  42. import classes.HolonObject;
  43. import ui.controller.Control;
  44. import utility.Random;
  45. import utility.ImageImport;
  46. public class Randomizer implements AddOn {
  47. private Control control;
  48. private int minAmountOfElements = 3;
  49. private int maxAmountOfElements = 7;
  50. private JPanel content = new JPanel();
  51. private JPanel tablePanel = new JPanel();
  52. private RandomPriotity prioPanel = new RandomPriotity();
  53. private JCheckBox priorityCheckbox = new JCheckBox("Random");
  54. private boolean useRandomPriority = true;
  55. //To Test the Layout Faster
  56. public static void main(String[] args)
  57. {
  58. JFrame newFrame = new JFrame("exampleWindow");
  59. Randomizer instance = new Randomizer();
  60. newFrame.setContentPane(instance.getPanel());
  61. newFrame.pack();
  62. newFrame.setVisible(true);
  63. newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  64. }
  65. private File file;
  66. public double randomChance = 1.0;
  67. private HashMap<HolonObject, Boolean> objectMap = new HashMap<HolonObject, Boolean>();
  68. private List<JCheckBox> checkboxList = new ArrayList<JCheckBox>();
  69. public Randomizer(){
  70. for(int i = 0; i < 30; i++) {
  71. objectMap.put(new HolonObject("dude"), true);
  72. }
  73. content.setLayout(new BorderLayout());
  74. JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, createParameterPanel(), createFilterPanel());
  75. splitPane.setDividerLocation(0.5);
  76. content.add(splitPane, BorderLayout.CENTER);
  77. JButton buttonRun = new JButton("Run");
  78. buttonRun.addActionListener(actionEvent -> run());
  79. content.add(buttonRun, BorderLayout.PAGE_END);
  80. }
  81. private JScrollPane createFilterPanel() {
  82. //Table
  83. tablePanel.setLayout(new BoxLayout(tablePanel, BoxLayout.PAGE_AXIS));
  84. JScrollPane scrollPanel = new JScrollPane(tablePanel);
  85. scrollPanel.setPreferredSize(new Dimension(300,300));
  86. fillTablePanel();
  87. return scrollPanel;
  88. }
  89. private void fillTablePanel() {
  90. //Clear old Data
  91. tablePanel.removeAll();
  92. checkboxList.clear();
  93. //HeadPanel
  94. int lineSpace = 20;
  95. JPanel headPanel = new JPanel();
  96. headPanel.setLayout(new BoxLayout(headPanel, BoxLayout.LINE_AXIS));
  97. headPanel.add(new JLabel("FILTER"));
  98. JButton updateButton = new JButton();
  99. updateButton.setIcon(new ImageIcon(ImageImport.loadImage("Images/replace.png", 15, 15)));
  100. updateButton.addActionListener(action -> {
  101. this.updateFilterList();
  102. content.updateUI();
  103. });
  104. updateButton.setToolTipText("Manuel updates the filter list with all canvas objects.");
  105. headPanel.add(updateButton);
  106. headPanel.add(Box.createHorizontalGlue());
  107. headPanel.add(new JLabel("SelectAll"));
  108. JCheckBox selectAllCheckbox = new JCheckBox();
  109. selectAllCheckbox.setSelected(true);
  110. selectAllCheckbox.addItemListener(input -> checkboxList.forEach(box -> box.setSelected(selectAllCheckbox.isSelected())));
  111. headPanel.add(selectAllCheckbox);
  112. tablePanel.add(headPanel);
  113. //Entrys
  114. for(HolonObject hObject: objectMap.keySet().stream().sorted(Comparator.comparing(ob -> ob.getName())).collect(Collectors.toList())) {
  115. //Entry
  116. JPanel entryPanel = new JPanel();
  117. entryPanel.setLayout(new BoxLayout(entryPanel, BoxLayout.LINE_AXIS));
  118. JLabel label = new JLabel(hObject.getName() + "[" + hObject.getId() + "]", new ImageIcon(ImageImport.loadImage(hObject.getImage(), lineSpace, lineSpace)), JLabel.LEFT);
  119. entryPanel.add(label);
  120. entryPanel.add(Box.createHorizontalGlue());
  121. JCheckBox checkbox = new JCheckBox();
  122. checkbox.setSelected(true);
  123. checkbox.addItemListener(change -> {
  124. objectMap.put(hObject, checkbox.isSelected());
  125. System.out.println("hObject:" + hObject + " changed to " + checkbox.isSelected());
  126. });
  127. checkboxList.add(checkbox);
  128. entryPanel.add(checkbox);
  129. tablePanel.add(entryPanel);
  130. }
  131. }
  132. private JSplitPane createParameterPanel() {
  133. JPanel choosePanel = new JPanel(null);
  134. choosePanel.setPreferredSize(new Dimension(300,200));
  135. choosePanel.setMinimumSize(new Dimension(300,200));
  136. JLabel minAmount = new JLabel("minAmountOfElements:");
  137. minAmount.setBounds(20, 60 , 200, 20);
  138. choosePanel.add(minAmount);
  139. JLabel maxAmount = new JLabel("maxAmountOfElements:");
  140. maxAmount.setBounds(20, 85 , 200, 20);
  141. choosePanel.add(maxAmount);
  142. //Integer formatter
  143. NumberFormat format = NumberFormat.getIntegerInstance();
  144. format.setGroupingUsed(false);
  145. format.setParseIntegerOnly(true);
  146. NumberFormatter integerFormatter = new NumberFormatter(format);
  147. integerFormatter.setMinimum(0);
  148. integerFormatter.setCommitsOnValidEdit(true);
  149. JFormattedTextField minAmountTextField = new JFormattedTextField(integerFormatter);
  150. minAmountTextField.setValue(this.minAmountOfElements);
  151. minAmountTextField.setToolTipText("Only positive Integer.");
  152. minAmountTextField.addPropertyChangeListener(actionEvent -> this.minAmountOfElements = Integer.parseInt(minAmountTextField.getValue().toString()));
  153. minAmountTextField.setBounds(220, 60, 50, 20);
  154. choosePanel.add(minAmountTextField);
  155. JFormattedTextField maxAmountTextField = new JFormattedTextField(integerFormatter);
  156. maxAmountTextField.setValue(this.maxAmountOfElements);
  157. maxAmountTextField.setToolTipText("Only positive Integer.");
  158. maxAmountTextField.addPropertyChangeListener(actionEvent -> this.maxAmountOfElements = Integer.parseInt(maxAmountTextField.getValue().toString()));
  159. maxAmountTextField.setBounds(220, 85, 50, 20);
  160. choosePanel.add(maxAmountTextField);
  161. JButton chooseFileButton = new JButton("Choose File");
  162. chooseFileButton.setBounds(20, 10, 200, 30);
  163. chooseFileButton.addActionListener(actionEvent -> file = openCatalogFile());
  164. choosePanel.add(chooseFileButton);
  165. JSlider bitSlider = createFlipChanceSlider();
  166. bitSlider.setBounds(10, 110, 280, 80);
  167. choosePanel.add(bitSlider);
  168. JPanel prioritySelectionPanel = new JPanel();
  169. prioritySelectionPanel.setLayout(new BoxLayout(prioritySelectionPanel, BoxLayout.PAGE_AXIS));
  170. //priorityCheckbox.setAlignmentY(0.0f);
  171. //selection
  172. prioritySelectionPanel.add(this.priorityCheckbox);
  173. priorityCheckbox.addItemListener(change -> {
  174. prioPanel.setEnabled(priorityCheckbox.isSelected());
  175. useRandomPriority = priorityCheckbox.isSelected();
  176. });
  177. priorityCheckbox.setSelected(useRandomPriority);
  178. prioritySelectionPanel.add(prioPanel);
  179. JSplitPane parameterPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, choosePanel, prioritySelectionPanel);
  180. parameterPanel.setPreferredSize(new Dimension(600,200));
  181. return parameterPanel;
  182. }
  183. private void run() {
  184. List<HolonElementSketch> holonElementCatalog = new ArrayList<HolonElementSketch>();
  185. if(file == null)file = openCatalogFile();
  186. if(file == null) return;
  187. readCatalogFromJson(file, holonElementCatalog);
  188. holonElementCatalog.forEach(con -> con.checkValues());
  189. objectMap.forEach((hObject, state) ->{
  190. //Ignore Filtered objects
  191. System.out.println("hObject:" + hObject + " state:" + state);
  192. if(!state) {
  193. return;
  194. }
  195. //Randomize
  196. hObject.getElements().clear();
  197. int randomAmountOfElementsToAdd = Random.nextIntegerInRange(minAmountOfElements, maxAmountOfElements + 1);
  198. for(int i = 0; i < randomAmountOfElementsToAdd; i++) {
  199. HolonElement ele = holonElementCatalog.get(Random.nextIntegerInRange(0, holonElementCatalog.size())).createHolonElement(hObject, Random.nextDouble() < randomChance );
  200. if(this.useRandomPriority) ele.setPriority(prioPanel.getPriority());
  201. hObject.getElements().add(ele);
  202. }
  203. });
  204. control.calculateStateAndVisualForCurrentTimeStep();
  205. control.updateCanvas();
  206. }
  207. private void fillObjectMap(List<AbstractCanvasObject> nodes) {
  208. for (AbstractCanvasObject aCps : nodes) {
  209. if (aCps instanceof HolonObject) {
  210. HolonObject hO = (HolonObject) aCps;
  211. objectMap.put(hO, true);
  212. }
  213. else if(aCps instanceof GroupNode) {
  214. fillObjectMap(((GroupNode)aCps).getNodes());
  215. }
  216. }
  217. }
  218. public void updateFilterList() {
  219. objectMap.clear();
  220. if(control != null)
  221. fillObjectMap(control.getModel().getObjectsOnCanvas());
  222. this.fillTablePanel();
  223. }
  224. @Override
  225. public JPanel getPanel() {
  226. return content;
  227. }
  228. @Override
  229. public void setController(Control control) {
  230. this.control = control;
  231. //Update Filter List
  232. updateFilterList();
  233. }
  234. private JSlider createFlipChanceSlider() {
  235. JSlider flipChance =new JSlider(JSlider.HORIZONTAL,0, 100, 100);
  236. flipChance.setBorder(BorderFactory.createTitledBorder("ActiveProbability"));
  237. flipChance.setMajorTickSpacing(50);
  238. flipChance.setMinorTickSpacing(5);
  239. flipChance.setPaintTicks(true);
  240. Hashtable<Integer, JLabel> labelTable = new Hashtable<Integer, JLabel>();
  241. labelTable.put( Integer.valueOf(0), new JLabel("0.0") );
  242. labelTable.put( Integer.valueOf(50), new JLabel("0.5") );
  243. labelTable.put( Integer.valueOf(100), new JLabel("1.0") );
  244. flipChance.setToolTipText("" +randomChance);
  245. flipChance.addChangeListener(actionEvent ->{
  246. randomChance =(double)flipChance.getValue()/100.0;
  247. flipChance.setToolTipText("" +randomChance);
  248. });
  249. flipChance.setLabelTable( labelTable );
  250. flipChance.setPaintLabels(true);
  251. return flipChance;
  252. }
  253. private void readCatalogFromJson(File file, List<HolonElementSketch> catalog) {
  254. Gson gson = new Gson();
  255. JsonParser parser = new JsonParser();
  256. try {
  257. JsonElement jsonTreeRoot = parser.parse(new FileReader(file));
  258. if(jsonTreeRoot.isJsonArray()) {
  259. JsonArray jsonArray = jsonTreeRoot.getAsJsonArray();
  260. jsonArray.forEach(jsonObject -> {
  261. HolonElementSketch newObject= gson.fromJson( jsonObject, HolonElementSketch.class);
  262. System.out.println(gson.toJson(newObject));
  263. catalog.add(newObject);
  264. });
  265. }
  266. } catch (JsonSyntaxException e) {
  267. e.printStackTrace();
  268. } catch (JsonIOException e) {
  269. e.printStackTrace();
  270. } catch (FileNotFoundException e) {
  271. e.printStackTrace();
  272. }
  273. }
  274. public File openCatalogFile() {
  275. JFileChooser fileChooser = new JFileChooser();
  276. fileChooser.setCurrentDirectory(new File(System.getProperty("user.dir")+"/randomizerConfigFiles/"));
  277. fileChooser.setFileFilter(new FileNameExtensionFilter("JSON Files", "json"));
  278. fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
  279. fileChooser.setAcceptAllFileFilterUsed(false);
  280. int result = fileChooser.showOpenDialog(content);
  281. if(result == JFileChooser.APPROVE_OPTION) {
  282. //Found a file
  283. return fileChooser.getSelectedFile();
  284. }
  285. return null;
  286. }
  287. }