List of usage examples for javax.swing JButton doClick
public void doClick()
From source file:components.ListDialog.java
private ListDialog(Frame frame, Component locationComp, String labelText, String title, Object[] data, String initialValue, String longValue) { super(frame, title, true); //Create and initialize the buttons. JButton cancelButton = new JButton("Cancel"); cancelButton.addActionListener(this); ///*from www . j a v a 2 s . c om*/ final JButton setButton = new JButton("Set"); setButton.setActionCommand("Set"); setButton.addActionListener(this); getRootPane().setDefaultButton(setButton); //main part of the dialog list = new JList(data) { //Subclass JList to workaround bug 4832765, which can cause the //scroll pane to not let the user easily scroll up to the beginning //of the list. An alternative would be to set the unitIncrement //of the JScrollBar to a fixed value. You wouldn't get the nice //aligned scrolling, but it should work. public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { int row; if (orientation == SwingConstants.VERTICAL && direction < 0 && (row = getFirstVisibleIndex()) != -1) { Rectangle r = getCellBounds(row, row); if ((r.y == visibleRect.y) && (row != 0)) { Point loc = r.getLocation(); loc.y--; int prevIndex = locationToIndex(loc); Rectangle prevR = getCellBounds(prevIndex, prevIndex); if (prevR == null || prevR.y >= r.y) { return 0; } return prevR.height; } } return super.getScrollableUnitIncrement(visibleRect, orientation, direction); } }; list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); if (longValue != null) { list.setPrototypeCellValue(longValue); //get extra space } list.setLayoutOrientation(JList.HORIZONTAL_WRAP); list.setVisibleRowCount(-1); list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { setButton.doClick(); //emulate button click } } }); JScrollPane listScroller = new JScrollPane(list); listScroller.setPreferredSize(new Dimension(250, 80)); listScroller.setAlignmentX(LEFT_ALIGNMENT); //Create a container so that we can add a title around //the scroll pane. Can't add a title directly to the //scroll pane because its background would be white. //Lay out the label and scroll pane from top to bottom. JPanel listPane = new JPanel(); listPane.setLayout(new BoxLayout(listPane, BoxLayout.PAGE_AXIS)); JLabel label = new JLabel(labelText); label.setLabelFor(list); listPane.add(label); listPane.add(Box.createRigidArea(new Dimension(0, 5))); listPane.add(listScroller); listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); //Lay out the buttons from left to right. JPanel buttonPane = new JPanel(); buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.LINE_AXIS)); buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10)); buttonPane.add(Box.createHorizontalGlue()); buttonPane.add(cancelButton); buttonPane.add(Box.createRigidArea(new Dimension(10, 0))); buttonPane.add(setButton); //Put everything together, using the content pane's BorderLayout. Container contentPane = getContentPane(); contentPane.add(listPane, BorderLayout.CENTER); contentPane.add(buttonPane, BorderLayout.PAGE_END); //Initialize values. setValue(initialValue); pack(); setLocationRelativeTo(locationComp); }
From source file:com.tascape.qa.th.android.driver.App.java
/** * The method starts a GUI to let an user inspect element tree and take screenshot when the user is interacting * with the app-under-test manually. Please make sure to set timeout long enough for manual interaction. * * @param timeoutMinutes timeout in minutes to fail the manual steps * * @throws Exception if case of error/* w w w . j a va 2 s .c o m*/ */ public void interactManually(int timeoutMinutes) throws Exception { LOG.info("Start manual UI interaction"); long end = System.currentTimeMillis() + timeoutMinutes * 60000L; AtomicBoolean visible = new AtomicBoolean(true); AtomicBoolean pass = new AtomicBoolean(false); String tName = Thread.currentThread().getName() + "m"; SwingUtilities.invokeLater(() -> { JDialog jd = new JDialog((JFrame) null, "Manual Device UI Interaction - " + device.getProductDetail()); jd.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); JPanel jpContent = new JPanel(new BorderLayout()); jd.setContentPane(jpContent); jpContent.setPreferredSize(new Dimension(1088, 828)); jpContent.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); JPanel jpInfo = new JPanel(); jpContent.add(jpInfo, BorderLayout.PAGE_START); jpInfo.setLayout(new BorderLayout()); { JButton jb = new JButton("PASS"); jb.setForeground(Color.green.darker()); jb.setFont(jb.getFont().deriveFont(Font.BOLD)); jpInfo.add(jb, BorderLayout.LINE_START); jb.addActionListener(event -> { pass.set(true); jd.dispose(); visible.set(false); }); } { JButton jb = new JButton("FAIL"); jb.setForeground(Color.red); jb.setFont(jb.getFont().deriveFont(Font.BOLD)); jpInfo.add(jb, BorderLayout.LINE_END); jb.addActionListener(event -> { pass.set(false); jd.dispose(); visible.set(false); }); } JLabel jlTimeout = new JLabel("xxx seconds left", SwingConstants.CENTER); jpInfo.add(jlTimeout, BorderLayout.CENTER); jpInfo.add(jlTimeout, BorderLayout.CENTER); new SwingWorker<Long, Long>() { @Override protected Long doInBackground() throws Exception { while (System.currentTimeMillis() < end) { Thread.sleep(1000); long left = (end - System.currentTimeMillis()) / 1000; this.publish(left); } return 0L; } @Override protected void process(List<Long> chunks) { Long l = chunks.get(chunks.size() - 1); jlTimeout.setText(l + " seconds left"); if (l < 850) { jlTimeout.setForeground(Color.red); } } }.execute(); JPanel jpResponse = new JPanel(new BorderLayout()); JPanel jpProgress = new JPanel(new BorderLayout()); jpResponse.add(jpProgress, BorderLayout.PAGE_START); JTextArea jtaJson = new JTextArea(); jtaJson.setEditable(false); jtaJson.setTabSize(4); Font font = jtaJson.getFont(); jtaJson.setFont(new Font("Courier New", font.getStyle(), font.getSize())); JTree jtView = new JTree(); JTabbedPane jtp = new JTabbedPane(); jtp.add("tree", new JScrollPane(jtView)); jtp.add("json", new JScrollPane(jtaJson)); jpResponse.add(jtp, BorderLayout.CENTER); JPanel jpScreen = new JPanel(); jpScreen.setMinimumSize(new Dimension(200, 200)); jpScreen.setLayout(new BoxLayout(jpScreen, BoxLayout.PAGE_AXIS)); JScrollPane jsp1 = new JScrollPane(jpScreen); jpResponse.add(jsp1, BorderLayout.LINE_START); JPanel jpJs = new JPanel(new BorderLayout()); JTextArea jtaJs = new JTextArea(); jpJs.add(new JScrollPane(jtaJs), BorderLayout.CENTER); JSplitPane jSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, jpResponse, jpJs); jSplitPane.setResizeWeight(0.88); jpContent.add(jSplitPane, BorderLayout.CENTER); JPanel jpLog = new JPanel(); jpLog.setBorder(BorderFactory.createEmptyBorder(5, 0, 0, 0)); jpLog.setLayout(new BoxLayout(jpLog, BoxLayout.LINE_AXIS)); JCheckBox jcbTap = new JCheckBox("Enable Click", null, false); jpLog.add(jcbTap); jpLog.add(Box.createHorizontalStrut(8)); JButton jbLogUi = new JButton("Log Screen"); jpResponse.add(jpLog, BorderLayout.PAGE_END); { jpLog.add(jbLogUi); jbLogUi.addActionListener((ActionEvent event) -> { jtaJson.setText("waiting for screenshot..."); Thread t = new Thread(tName) { @Override public void run() { LOG.debug("\n\n"); try { WindowHierarchy wh = device.loadWindowHierarchy(); jtView.setModel(getModel(wh)); jtaJson.setText(""); jtaJson.append(wh.root.toJson().toString(2)); jtaJson.append("\n"); File png = device.takeDeviceScreenshot(); BufferedImage image = ImageIO.read(png); int w = device.getDisplayWidth(); int h = device.getDisplayHeight(); BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); Graphics2D g2 = resizedImg.createGraphics(); g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2.drawImage(image, 0, 0, w, h, null); g2.dispose(); JLabel jLabel = new JLabel(new ImageIcon(resizedImg)); jpScreen.removeAll(); jsp1.setPreferredSize(new Dimension(w + 30, h)); jpScreen.add(jLabel); jLabel.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { LOG.debug("clicked at {},{}", e.getPoint().getX(), e.getPoint().getY()); if (jcbTap.isSelected()) { device.click(e.getPoint().x, e.getPoint().y); device.waitForIdle(); jbLogUi.doClick(); } } }); } catch (Exception ex) { LOG.error("Cannot log screen", ex); jtaJson.append("Cannot log screen"); } jtaJson.append("\n\n\n"); LOG.debug("\n\n"); jd.setSize(jd.getBounds().width + 1, jd.getBounds().height + 1); jd.setSize(jd.getBounds().width - 1, jd.getBounds().height - 1); } }; t.start(); }); } jpLog.add(Box.createHorizontalStrut(38)); { JButton jbLogMsg = new JButton("Log Message"); jpLog.add(jbLogMsg); JTextField jtMsg = new JTextField(10); jpLog.add(jtMsg); jtMsg.addFocusListener(new FocusListener() { @Override public void focusLost(final FocusEvent pE) { } @Override public void focusGained(final FocusEvent pE) { jtMsg.selectAll(); } }); jtMsg.addKeyListener(new KeyAdapter() { @Override public void keyPressed(java.awt.event.KeyEvent e) { if (e.getKeyCode() == java.awt.event.KeyEvent.VK_ENTER) { jbLogMsg.doClick(); } } }); jbLogMsg.addActionListener(event -> { Thread t = new Thread(tName) { @Override public void run() { String msg = jtMsg.getText(); if (StringUtils.isNotBlank(msg)) { LOG.info("{}", msg); jtMsg.selectAll(); } } }; t.start(); try { t.join(); } catch (InterruptedException ex) { LOG.error("Cannot take screenshot", ex); } jtMsg.requestFocus(); }); } jpLog.add(Box.createHorizontalStrut(38)); { JButton jbClear = new JButton("Clear"); jpLog.add(jbClear); jbClear.addActionListener(event -> { jtaJson.setText(""); }); } JPanel jpAction = new JPanel(); jpContent.add(jpAction, BorderLayout.PAGE_END); jpAction.setLayout(new BoxLayout(jpAction, BoxLayout.LINE_AXIS)); jpJs.add(jpAction, BorderLayout.PAGE_END); jd.pack(); jd.setVisible(true); jd.setLocationRelativeTo(null); jbLogUi.doClick(); }); while (visible.get()) { if (System.currentTimeMillis() > end) { LOG.error("Manual UI interaction timeout"); break; } Thread.sleep(500); } if (pass.get()) { LOG.info("Manual UI Interaction returns PASS"); } else { Assert.fail("Manual UI Interaction returns FAIL"); } }
From source file:com._17od.upm.gui.AccountDialog.java
public AccountDialog(AccountInformation account, JFrame parentWindow, boolean readOnly, ArrayList existingAccounts) { super(parentWindow, true); boolean addingAccount = false; //Request focus on Account JDialog when mouse clicked this.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) { requestFocus();//from w ww.j a v a 2 s. c o m } } }); // Set the title based on weather we've been opened in readonly mode and // weather the // Account passed in is empty or not String title = null; if (readOnly) { title = Translator.translate("viewAccount"); } else if (!readOnly && account.getAccountName().trim().equals("")) { title = Translator.translate("addAccount"); addingAccount = true; } else { title = Translator.translate("editAccount"); } setTitle(title); this.pAccount = account; this.existingAccounts = existingAccounts; this.parentWindow = parentWindow; getContentPane().setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); Container container = getContentPane(); // The AccountName Row JLabel accountLabel = new JLabel(Translator.translate("account")); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; container.add(accountLabel, c); // This panel will hold the Account field and the copy and paste // buttons. JPanel accountPanel = new JPanel(new GridBagLayout()); accountName = new JTextField(new String(pAccount.getAccountName()), 20); if (readOnly) { accountName.setEditable(false); } c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; accountPanel.add(accountName, c); accountName.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { accountName.selectAll(); } }); JButton acctCopyButton = new JButton(); acctCopyButton.setIcon(Util.loadImage("copy-icon.png")); acctCopyButton.setToolTipText("Copy"); acctCopyButton.setEnabled(true); acctCopyButton.setMargin(new Insets(0, 0, 0, 0)); acctCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { copyTextField(accountName); } }); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; accountPanel.add(acctCopyButton, c); JButton acctPasteButton = new JButton(); acctPasteButton.setIcon(Util.loadImage("paste-icon.png")); acctPasteButton.setToolTipText("Paste"); acctPasteButton.setEnabled(!readOnly); acctPasteButton.setMargin(new Insets(0, 0, 0, 0)); acctPasteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { pasteToTextField(accountName); } }); c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; accountPanel.add(acctPasteButton, c); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; container.add(accountPanel, c); // Userid Row JLabel useridLabel = new JLabel(Translator.translate("userid")); c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; container.add(useridLabel, c); // This panel will hold the User ID field and the copy and paste // buttons. JPanel idPanel = new JPanel(new GridBagLayout()); userId = new JTextField(new String(pAccount.getUserId()), 20); if (readOnly) { userId.setEditable(false); } c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; idPanel.add(userId, c); userId.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { userId.selectAll(); } }); JButton idCopyButton = new JButton(); idCopyButton.setIcon(Util.loadImage("copy-icon.png")); idCopyButton.setToolTipText("Copy"); idCopyButton.setEnabled(true); idCopyButton.setMargin(new Insets(0, 0, 0, 0)); idCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { copyTextField(userId); } }); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; idPanel.add(idCopyButton, c); JButton idPasteButton = new JButton(); idPasteButton.setIcon(Util.loadImage("paste-icon.png")); idPasteButton.setToolTipText("Paste"); idPasteButton.setEnabled(!readOnly); idPasteButton.setMargin(new Insets(0, 0, 0, 0)); idPasteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { pasteToTextField(userId); } }); c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; idPanel.add(idPasteButton, c); c.gridx = 1; c.gridy = 1; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; container.add(idPanel, c); // Password Row JLabel passwordLabel = new JLabel(Translator.translate("password")); c.gridx = 0; c.gridy = 2; c.anchor = GridBagConstraints.FIRST_LINE_START; c.insets = new Insets(15, 10, 10, 10); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; container.add(passwordLabel, c); // This panel will hold the password, generate password button, copy and // paste buttons, and hide password checkbox JPanel passwordPanel = new JPanel(new GridBagLayout()); password = new JPasswordField(new String(pAccount.getPassword()), 20); // allow CTRL-C on the password field password.putClientProperty("JPasswordField.cutCopyAllowed", Boolean.TRUE); password.setEditable(!readOnly); password.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { password.selectAll(); } }); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 1; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; passwordPanel.add(password, c); JButton generateRandomPasswordButton = new JButton(Translator.translate("generate")); if (readOnly) { generateRandomPasswordButton.setEnabled(false); } generateRandomPasswordButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent actionevent) { // Get the user's preference about including or not Escape // Characters to generated passwords Boolean includeEscapeChars = new Boolean( Preferences.get(Preferences.ApplicationOptions.INCLUDE_ESCAPE_CHARACTERS, "true")); int pwLength = Preferences.getInt(Preferences.ApplicationOptions.ACCOUNT_PASSWORD_LENGTH, 8); String Password; if ((includeEscapeChars.booleanValue()) && (pwLength > 3)) { // Verify that the generated password satisfies the criteria // for strong passwords(including Escape Characters) do { Password = GeneratePassword(pwLength, includeEscapeChars.booleanValue()); } while (!(CheckPassStrong(Password, includeEscapeChars.booleanValue()))); } else if (!(includeEscapeChars.booleanValue()) && (pwLength > 2)) { // Verify that the generated password satisfies the criteria // for strong passwords(excluding Escape Characters) do { Password = GeneratePassword(pwLength, includeEscapeChars.booleanValue()); } while (!(CheckPassStrong(Password, includeEscapeChars.booleanValue()))); } else { // Else a weak password of 3 or less chars will be produced Password = GeneratePassword(pwLength, includeEscapeChars.booleanValue()); } password.setText(Password); } }); if (addingAccount) { generateRandomPasswordButton.doClick(); } c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; passwordPanel.add(generateRandomPasswordButton, c); JButton pwCopyButton = new JButton(); pwCopyButton.setIcon(Util.loadImage("copy-icon.png")); pwCopyButton.setToolTipText("Copy"); pwCopyButton.setEnabled(true); pwCopyButton.setMargin(new Insets(0, 0, 0, 0)); pwCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { copyTextField(password); } }); c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; passwordPanel.add(pwCopyButton, c); JButton pwPasteButton = new JButton(); pwPasteButton.setIcon(Util.loadImage("paste-icon.png")); pwPasteButton.setToolTipText("Paste"); pwPasteButton.setEnabled(!readOnly); pwPasteButton.setMargin(new Insets(0, 0, 0, 0)); pwPasteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { pasteToTextField(password); } }); c.gridx = 3; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; passwordPanel.add(pwPasteButton, c); JCheckBox hidePasswordCheckbox = new JCheckBox(Translator.translate("hide"), true); defaultEchoChar = password.getEchoChar(); hidePasswordCheckbox.setMargin(new Insets(5, 0, 5, 0)); hidePasswordCheckbox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { password.setEchoChar(defaultEchoChar); } else { password.setEchoChar((char) 0); } } }); Boolean hideAccountPassword = new Boolean( Preferences.get(Preferences.ApplicationOptions.ACCOUNT_HIDE_PASSWORD, "true")); hidePasswordCheckbox.setSelected(hideAccountPassword.booleanValue()); c.gridx = 0; c.gridy = 1; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 0); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; passwordPanel.add(hidePasswordCheckbox, c); c.gridx = 1; c.gridy = 2; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 1; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; container.add(passwordPanel, c); // URL Row JLabel urlLabel = new JLabel(Translator.translate("url")); c.gridx = 0; c.gridy = 3; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; container.add(urlLabel, c); // This panel will hold the URL field and the copy and paste buttons. JPanel urlPanel = new JPanel(new GridBagLayout()); url = new JTextField(new String(pAccount.getUrl()), 20); if (readOnly) { url.setEditable(false); } c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; urlPanel.add(url, c); url.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { url.selectAll(); } }); final JButton urlLaunchButton = new JButton(); urlLaunchButton.setIcon(Util.loadImage("launch-url-sm.png")); urlLaunchButton.setToolTipText("Launch URL"); urlLaunchButton.setEnabled(true); urlLaunchButton.setMargin(new Insets(0, 0, 0, 0)); urlLaunchButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { String urlText = url.getText(); // Check if the selected url is null or emty and inform the user // via JoptioPane message if ((urlText == null) || (urlText.length() == 0)) { JOptionPane.showMessageDialog(urlLaunchButton.getParent(), Translator.translate("EmptyUrlJoptionpaneMsg"), Translator.translate("UrlErrorJoptionpaneTitle"), JOptionPane.WARNING_MESSAGE); // Check if the selected url is a valid formated url(via // urlIsValid() method) and inform the user via JoptioPane // message } else if (!(urlIsValid(urlText))) { JOptionPane.showMessageDialog(urlLaunchButton.getParent(), Translator.translate("InvalidUrlJoptionpaneMsg"), Translator.translate("UrlErrorJoptionpaneTitle"), JOptionPane.WARNING_MESSAGE); // Call the method LaunchSelectedURL() using the selected // url as input } else { LaunchSelectedURL(urlText); } } }); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; urlPanel.add(urlLaunchButton, c); JButton urlCopyButton = new JButton(); urlCopyButton.setIcon(Util.loadImage("copy-icon.png")); urlCopyButton.setToolTipText("Copy"); urlCopyButton.setEnabled(true); urlCopyButton.setMargin(new Insets(0, 0, 0, 0)); urlCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { copyTextField(url); } }); c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; urlPanel.add(urlCopyButton, c); JButton urlPasteButton = new JButton(); urlPasteButton.setIcon(Util.loadImage("paste-icon.png")); urlPasteButton.setToolTipText("Paste"); urlPasteButton.setEnabled(!readOnly); urlPasteButton.setMargin(new Insets(0, 0, 0, 0)); urlPasteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { pasteToTextField(url); } }); c.gridx = 3; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; urlPanel.add(urlPasteButton, c); c.gridx = 1; c.gridy = 3; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; container.add(urlPanel, c); // Notes Row JLabel notesLabel = new JLabel(Translator.translate("notes")); c.gridx = 0; c.gridy = 4; c.anchor = GridBagConstraints.FIRST_LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; container.add(notesLabel, c); // This panel will hold the Notes text area and the copy and paste // buttons. JPanel notesPanel = new JPanel(new GridBagLayout()); notes = new JTextArea(new String(pAccount.getNotes()), 10, 20); if (readOnly) { notes.setEditable(false); } notes.setLineWrap(true); // Enable line wrapping. notes.setWrapStyleWord(true); // Line wrap at whitespace. JScrollPane notesScrollPane = new JScrollPane(notes); c.gridx = 0; c.gridy = 0; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.BOTH; notesPanel.add(notesScrollPane, c); JButton notesCopyButton = new JButton(); notesCopyButton.setIcon(Util.loadImage("copy-icon.png")); notesCopyButton.setToolTipText("Copy"); notesCopyButton.setEnabled(true); notesCopyButton.setMargin(new Insets(0, 0, 0, 0)); notesCopyButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { copyTextArea(notes); } }); c.gridx = 1; c.gridy = 0; c.anchor = GridBagConstraints.FIRST_LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; notesPanel.add(notesCopyButton, c); JButton notesPasteButton = new JButton(); notesPasteButton.setIcon(Util.loadImage("paste-icon.png")); notesPasteButton.setToolTipText("Paste"); notesPasteButton.setEnabled(!readOnly); notesPasteButton.setMargin(new Insets(0, 0, 0, 0)); notesPasteButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { pasteToTextArea(notes); } }); c.gridx = 2; c.gridy = 0; c.anchor = GridBagConstraints.FIRST_LINE_START; c.insets = new Insets(0, 0, 0, 5); c.weightx = 0; c.weighty = 0; c.gridwidth = 1; c.fill = GridBagConstraints.NONE; notesPanel.add(notesPasteButton, c); c.gridx = 1; c.gridy = 4; c.anchor = GridBagConstraints.LINE_START; c.insets = new Insets(10, 10, 10, 10); c.weightx = 1; c.weighty = 1; c.gridwidth = 1; c.fill = GridBagConstraints.HORIZONTAL; container.add(notesPanel, c); // Seperator Row JSeparator sep = new JSeparator(); c.gridx = 0; c.gridy = 5; c.anchor = GridBagConstraints.PAGE_END; c.insets = new Insets(0, 0, 0, 0); c.weightx = 0; c.weighty = 0; c.gridwidth = 3; c.fill = GridBagConstraints.HORIZONTAL; container.add(sep, c); // Button Row JPanel buttonPanel = new JPanel(); JButton okButton = new JButton(Translator.translate("ok")); // Link Enter key to okButton getRootPane().setDefaultButton(okButton); okButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { okButtonAction(); } }); buttonPanel.add(okButton); if (!readOnly) { JButton cancelButton = new JButton(Translator.translate("cancel")); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { closeButtonAction(); } }); buttonPanel.add(cancelButton); } c.gridx = 0; c.gridy = 6; c.anchor = GridBagConstraints.PAGE_END; c.insets = new Insets(5, 0, 5, 0); c.weightx = 0; c.weighty = 0; c.gridwidth = 3; c.fill = GridBagConstraints.NONE; container.add(buttonPanel, c); }
From source file:jgnash.ui.report.compiled.PayeePieChart.java
private JPanel createPanel() { JButton refreshButton = new JButton(rb.getString("Button.Refresh")); JButton addFilterButton = new JButton(rb.getString("Button.AddFilter")); final JButton saveButton = new JButton(rb.getString("Button.SaveFilters")); JButton deleteFilterButton = new JButton(rb.getString("Button.DeleteFilter")); JButton clearPrefButton = new JButton(rb.getString("Button.MasterDelete")); filterCombo = new JComboBox<>(); startField = new DatePanel(); endField = new DatePanel(); txtAddFilter = new TextField(); filterList = new ArrayList<>(); filtersChanged = false;//from w w w . j ava2s . c o m useFilters = new JCheckBox(rb.getString("Label.UseFilters")); useFilters.setSelected(true); showPercentCheck = new JCheckBox(rb.getString("Button.ShowPercentValues")); combo = AccountListComboBox.getFullInstance(); final LocalDate dStart = DateUtils.getFirstDayOfTheMonth(LocalDate.now().minusYears(1)); long start = pref.getLong(START_DATE, DateUtils.asEpochMilli(dStart)); startField.setDate(DateUtils.asLocalDate(start)); currentAccount = combo.getSelectedAccount(); PieDataset[] data = createPieDataSet(currentAccount); JFreeChart chartCredit = createPieChart(currentAccount, data, 0); chartPanelCredit = new ChartPanel(chartCredit, true, true, true, false, true); // (chart, properties, save, print, zoom, tooltips) JFreeChart chartDebit = createPieChart(currentAccount, data, 1); chartPanelDebit = new ChartPanel(chartDebit, true, true, true, false, true); FormLayout layout = new FormLayout("p, $lcgap, 70dlu, 8dlu, p, $lcgap, 70dlu, $ugap, p, $lcgap:g, left:p", "d, $rgap, d, $ugap, f:p:g, $rgap, d"); DefaultFormBuilder builder = new DefaultFormBuilder(layout); layout.setRowGroups(new int[][] { { 1, 3 } }); // row 1 builder.append(combo, 9); builder.append(useFilters); builder.nextLine(); builder.nextLine(); // row 3 builder.append(rb.getString("Label.StartDate"), startField); builder.append(rb.getString("Label.EndDate"), endField); builder.append(refreshButton); builder.append(showPercentCheck); builder.nextLine(); builder.nextLine(); // row 5 FormLayout subLayout = new FormLayout("180dlu:g, 1dlu, 180dlu:g", "f:180dlu:g"); DefaultFormBuilder subBuilder = new DefaultFormBuilder(subLayout); subBuilder.append(chartPanelCredit); subBuilder.append(chartPanelDebit); builder.append(subBuilder.getPanel(), 11); builder.nextLine(); builder.nextLine(); // row 7 builder.append(txtAddFilter, 3); builder.append(addFilterButton, 3); builder.append(saveButton); builder.nextLine(); // row builder.append(filterCombo, 3); builder.append(deleteFilterButton, 3); builder.append(clearPrefButton); builder.nextLine(); JPanel panel = builder.getPanel(); combo.addActionListener(e -> { Account newAccount = combo.getSelectedAccount(); if (filtersChanged) { int result = JOptionPane.showConfirmDialog(null, rb.getString("Message.SaveFilters"), "Warning", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { saveButton.doClick(); } } filtersChanged = false; String[] list = POUND_DELIMITER_PATTERN.split(pref.get(FILTER_TAG + newAccount.hashCode(), "")); filterList.clear(); for (String filter : list) { if (!filter.isEmpty()) { //System.out.println("Adding filter: #" + filter + "#"); filterList.add(filter); } } refreshFilters(); setCurrentAccount(newAccount); pref.putLong(START_DATE, DateUtils.asEpochMilli(startField.getLocalDate())); }); refreshButton.addActionListener(e -> { setCurrentAccount(currentAccount); pref.putLong(START_DATE, DateUtils.asEpochMilli(startField.getLocalDate())); }); clearPrefButton.addActionListener(e -> { int result = JOptionPane.showConfirmDialog(null, rb.getString("Message.MasterDelete"), "Warning", JOptionPane.YES_NO_OPTION); if (result == JOptionPane.YES_OPTION) { try { pref.clear(); } catch (Exception ex) { System.out.println("Exception clearing preferences" + ex); } } }); saveButton.addActionListener(e -> { final StringBuilder sb = new StringBuilder(); for (String filter : filterList) { sb.append(filter); sb.append('#'); } //System.out.println("Save = " + FILTER_TAG + currentAccount.hashCode() + " = " + sb.toString()); pref.put(FILTER_TAG + currentAccount.hashCode(), sb.toString()); filtersChanged = false; }); addFilterButton.addActionListener(e -> { String newFilter = txtAddFilter.getText(); filterList.remove(newFilter); if (!newFilter.isEmpty()) { filterList.add(newFilter); filtersChanged = true; txtAddFilter.setText(""); } refreshFilters(); }); deleteFilterButton.addActionListener(e -> { if (!filterList.isEmpty()) { String filter = (String) filterCombo.getSelectedItem(); filterList.remove(filter); filtersChanged = true; } refreshFilters(); }); useFilters.addActionListener(e -> setCurrentAccount(currentAccount)); showPercentCheck.addActionListener(e -> { ((PiePlot) chartPanelCredit.getChart().getPlot()) .setLabelGenerator(showPercentCheck.isSelected() ? percentLabels : defaultLabels); ((PiePlot) chartPanelDebit.getChart().getPlot()) .setLabelGenerator(showPercentCheck.isSelected() ? percentLabels : defaultLabels); }); return panel; }
From source file:userinterface.properties.GUIGraphHandler.java
public void defineConstantsAndPlot(Expression expr, JPanel graph, String seriesName, Boolean isNewGraph, boolean is2D) { JDialog dialog;//from w w w . ja v a 2 s . co m JButton ok, cancel; JScrollPane scrollPane; ConstantPickerList constantList; JComboBox<String> xAxis, yAxis; //init everything dialog = new JDialog(GUIPrism.getGUI()); dialog.setTitle("Define constants and select axes"); dialog.setSize(500, 400); dialog.setLocationRelativeTo(GUIPrism.getGUI()); dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS)); dialog.setModal(true); constantList = new ConstantPickerList(); scrollPane = new JScrollPane(constantList); xAxis = new JComboBox<String>(); yAxis = new JComboBox<String>(); ok = new JButton("Ok"); ok.setMnemonic('O'); cancel = new JButton("Cancel"); cancel.setMnemonic('C'); //add all components to their dedicated panels JPanel exprPanel = new JPanel(new FlowLayout()); exprPanel.setBorder(new TitledBorder("Function")); exprPanel.add(new JLabel(expr.toString())); JPanel axisPanel = new JPanel(); axisPanel.setBorder(new TitledBorder("Select axis constants")); axisPanel.setLayout(new BoxLayout(axisPanel, BoxLayout.Y_AXIS)); JPanel xAxisPanel = new JPanel(new FlowLayout()); xAxisPanel.add(new JLabel("X axis:")); xAxisPanel.add(xAxis); JPanel yAxisPanel = new JPanel(new FlowLayout()); yAxisPanel.add(new JLabel("Y axis:")); yAxisPanel.add(yAxis); axisPanel.add(xAxisPanel); axisPanel.add(yAxisPanel); JPanel constantPanel = new JPanel(new BorderLayout()); constantPanel.setBorder(new TitledBorder("Please define the following constants")); constantPanel.add(scrollPane, BorderLayout.CENTER); constantPanel.add(new ConstantHeader(), BorderLayout.NORTH); JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); bottomPanel.add(ok); bottomPanel.add(cancel); //fill the axes components for (int i = 0; i < expr.getAllConstants().size(); i++) { xAxis.addItem(expr.getAllConstants().get(i)); if (!is2D) yAxis.addItem(expr.getAllConstants().get(i)); } if (!is2D) { yAxis.setSelectedIndex(1); } //fill the constants table for (int i = 0; i < expr.getAllConstants().size(); i++) { ConstantLine line = new ConstantLine(expr.getAllConstants().get(i), TypeDouble.getInstance()); constantList.addConstant(line); if (!is2D) { if (line.getName().equals(xAxis.getSelectedItem().toString()) || line.getName().equals(yAxis.getSelectedItem().toString())) { line.doFuncEnables(false); } else { line.doFuncEnables(true); } } } //do enables if (is2D) { yAxis.setEnabled(false); } ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok"); ok.getActionMap().put("ok", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { ok.doClick(); } }); cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel"); cancel.getActionMap().put("cancel", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { cancel.doClick(); } }); //add action listeners xAxis.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (is2D) { return; } String item = xAxis.getSelectedItem().toString(); if (item.equals(yAxis.getSelectedItem().toString())) { int index = yAxis.getSelectedIndex(); if (index != yAxis.getItemCount() - 1) { yAxis.setSelectedIndex(++index); } else { yAxis.setSelectedIndex(--index); } } for (int i = 0; i < constantList.getNumConstants(); i++) { ConstantLine line = constantList.getConstantLine(i); if (line.getName().equals(xAxis.getSelectedItem().toString()) || line.getName().equals(yAxis.getSelectedItem().toString())) { line.doFuncEnables(false); } else { line.doFuncEnables(true); } } } }); yAxis.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String item = yAxis.getSelectedItem().toString(); if (item.equals(xAxis.getSelectedItem().toString())) { int index = xAxis.getSelectedIndex(); if (index != xAxis.getItemCount() - 1) { xAxis.setSelectedIndex(++index); } else { xAxis.setSelectedIndex(--index); } } for (int i = 0; i < constantList.getNumConstants(); i++) { ConstantLine line = constantList.getConstantLine(i); if (line.getName().equals(xAxis.getSelectedItem().toString()) || line.getName().equals(yAxis.getSelectedItem().toString())) { line.doFuncEnables(false); } else { line.doFuncEnables(true); } } } }); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { constantList.checkValid(); } catch (PrismException e2) { JOptionPane.showMessageDialog(dialog, "<html> One or more of the defined constants are invalid. <br><br> <font color=red>Error: </font>" + e2.getMessage() + "</html>", "Parse Error", JOptionPane.ERROR_MESSAGE); return; } if (is2D) { // it will always be a parametric graph in 2d case ParametricGraph pGraph = (ParametricGraph) graph; ConstantLine xAxisConstant = constantList.getConstantLine(xAxis.getSelectedItem().toString()); if (xAxisConstant == null) { //should never happen JOptionPane.showMessageDialog(dialog, "The selected axis is invalid.", "Error", JOptionPane.ERROR_MESSAGE); return; } double xStartValue = Double.parseDouble(xAxisConstant.getStartValue()); double xEndValue = Double.parseDouble(xAxisConstant.getEndValue()); double xStepValue = Double.parseDouble(xAxisConstant.getStepValue()); int seriesCount = 0; for (int i = 0; i < constantList.getNumConstants(); i++) { ConstantLine line = constantList.getConstantLine(i); if (line.getName().equals(xAxis.getSelectedItem().toString())) { seriesCount++; } else { seriesCount += line.getTotalNumOfValues(); } } // if there will be too many series to be plotted, ask the user if they are sure they know what they are doing if (seriesCount > 10) { int res = JOptionPane.showConfirmDialog(dialog, "This configuration will create " + seriesCount + " series. Continue?", "Confirm", JOptionPane.YES_NO_OPTION); if (res == JOptionPane.NO_OPTION) { return; } } Values singleValuesGlobal = new Values(); //add the single values to a global values list for (int i = 0; i < constantList.getNumConstants(); i++) { ConstantLine line = constantList.getConstantLine(i); if (line.getTotalNumOfValues() == 1) { double singleValue = Double.parseDouble(line.getSingleValue()); singleValuesGlobal.addValue(line.getName(), singleValue); } } // we just have one variable so we can plot directly if (constantList.getNumConstants() == 1 || singleValuesGlobal.getNumValues() == constantList.getNumConstants() - 1) { SeriesKey key = pGraph.addSeries(seriesName); pGraph.hideShape(key); pGraph.getXAxisSettings().setHeading(xAxis.getSelectedItem().toString()); pGraph.getYAxisSettings().setHeading("function"); for (double x = xStartValue; x <= xEndValue; x += xStepValue) { double ans = -1; Values vals = new Values(); vals.addValue(xAxis.getSelectedItem().toString(), x); for (int ii = 0; ii < singleValuesGlobal.getNumValues(); ii++) { try { vals.addValue(singleValuesGlobal.getName(ii), singleValuesGlobal.getDoubleValue(ii)); } catch (PrismLangException e1) { e1.printStackTrace(); } } try { ans = expr.evaluateDouble(vals); } catch (PrismLangException e1) { e1.printStackTrace(); } pGraph.addPointToSeries(key, new PrismXYDataItem(x, ans)); } if (isNewGraph) { addGraph(pGraph); } dialog.dispose(); return; } for (int i = 0; i < constantList.getNumConstants(); i++) { ConstantLine line = constantList.getConstantLine(i); if (line == xAxisConstant || singleValuesGlobal.contains(line.getName())) { continue; } double lineStart = Double.parseDouble(line.getStartValue()); double lineEnd = Double.parseDouble(line.getEndValue()); double lineStep = Double.parseDouble(line.getStepValue()); for (double j = lineStart; j < lineEnd; j += lineStep) { SeriesKey key = pGraph.addSeries(seriesName); pGraph.hideShape(key); for (double x = xStartValue; x <= xEndValue; x += xStepValue) { double ans = -1; Values vals = new Values(); vals.addValue(xAxis.getSelectedItem().toString(), x); vals.addValue(line.getName(), j); for (int ii = 0; ii < singleValuesGlobal.getNumValues(); ii++) { try { vals.addValue(singleValuesGlobal.getName(ii), singleValuesGlobal.getDoubleValue(ii)); } catch (PrismLangException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } for (int ii = 0; ii < constantList.getNumConstants(); ii++) { if (constantList.getConstantLine(ii) == xAxisConstant || singleValuesGlobal .contains(constantList.getConstantLine(ii).getName()) || constantList.getConstantLine(ii) == line) { continue; } ConstantLine temp = constantList.getConstantLine(ii); double val = Double.parseDouble(temp.getStartValue()); vals.addValue(temp.getName(), val); } try { ans = expr.evaluateDouble(vals); } catch (PrismLangException e1) { e1.printStackTrace(); } pGraph.addPointToSeries(key, new PrismXYDataItem(x, ans)); } } } if (isNewGraph) { addGraph(graph); } } else { // this will always be a parametric graph for the 3d case ParametricGraph3D pGraph = (ParametricGraph3D) graph; //add the graph to the gui addGraph(pGraph); //Get the constants we want to put on the x and y axis ConstantLine xAxisConstant = constantList.getConstantLine(xAxis.getSelectedItem().toString()); ConstantLine yAxisConstant = constantList.getConstantLine(yAxis.getSelectedItem().toString()); //add the single values to a global values list Values singleValuesGlobal = new Values(); for (int i = 0; i < constantList.getNumConstants(); i++) { ConstantLine line = constantList.getConstantLine(i); if (line.getTotalNumOfValues() == 1) { double singleValue = Double.parseDouble(line.getSingleValue()); singleValuesGlobal.addValue(line.getName(), singleValue); } } pGraph.setGlobalValues(singleValuesGlobal); pGraph.setAxisConstants(xAxis.getSelectedItem().toString(), yAxis.getSelectedItem().toString()); pGraph.setBounds(xAxisConstant.getStartValue(), xAxisConstant.getEndValue(), yAxisConstant.getStartValue(), yAxisConstant.getEndValue()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { //plot the graph pGraph.plot(expr.toString(), xAxis.getSelectedItem().toString(), "Function", yAxis.getSelectedItem().toString()); //calculate the sampling rates from the step sizes as given by the user int xSamples = (int) ((Double.parseDouble(xAxisConstant.getEndValue()) - Double.parseDouble(xAxisConstant.getStartValue())) / Double.parseDouble(xAxisConstant.getStepValue())); int ySamples = (int) ((Double.parseDouble(xAxisConstant.getEndValue()) - Double.parseDouble(xAxisConstant.getStartValue())) / Double.parseDouble(xAxisConstant.getStepValue())); pGraph.setSamplingRates(xSamples, ySamples); } }); } dialog.dispose(); } }); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.dispose(); } }); //add everything to the dialog show the dialog dialog.add(exprPanel); dialog.add(axisPanel); dialog.add(constantPanel); dialog.add(bottomPanel); dialog.setVisible(true); }
From source file:userinterface.properties.GUIGraphHandler.java
public void plotNewFunction() { JDialog dialog;//from w w w . j a v a 2s .c om JRadioButton radio2d, radio3d, newGraph, existingGraph; JTextField functionField, seriesName; JButton ok, cancel; JComboBox<String> chartOptions; JLabel example; //init all the fields of the dialog dialog = new JDialog(GUIPrism.getGUI()); radio2d = new JRadioButton("2D"); radio3d = new JRadioButton("3D"); newGraph = new JRadioButton("New Graph"); existingGraph = new JRadioButton("Exisiting"); chartOptions = new JComboBox<String>(); functionField = new JTextField(); ok = new JButton("Plot"); cancel = new JButton("Cancel"); seriesName = new JTextField(); example = new JLabel("<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>"); example.addMouseListener(new MouseAdapter() { @Override public void mouseEntered(MouseEvent e) { example.setCursor(new Cursor(Cursor.HAND_CURSOR)); example.setForeground(Color.BLUE); } @Override public void mouseExited(MouseEvent e) { example.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); example.setForeground(Color.BLACK); } @Override public void mouseClicked(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { if (radio2d.isSelected()) { functionField.setText("x/2 + 5"); } else { functionField.setText("x+y+5"); } functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15)); functionField.setForeground(Color.BLACK); } } }); //set dialog properties dialog.setSize(400, 350); dialog.setTitle("Plot a new function"); dialog.setModal(true); dialog.setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS)); dialog.setLocationRelativeTo(GUIPrism.getGUI()); //add every component to their dedicated panels JPanel graphTypePanel = new JPanel(new FlowLayout()); graphTypePanel.setBorder(BorderFactory .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function type")); graphTypePanel.add(radio2d); graphTypePanel.add(radio3d); JPanel functionFieldPanel = new JPanel(new BorderLayout()); functionFieldPanel.setBorder(BorderFactory .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Function")); functionFieldPanel.add(functionField, BorderLayout.CENTER); functionFieldPanel.add(example, BorderLayout.SOUTH); JPanel chartSelectPanel = new JPanel(); chartSelectPanel.setLayout(new BoxLayout(chartSelectPanel, BoxLayout.Y_AXIS)); chartSelectPanel.setBorder(BorderFactory .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Plot function to")); JPanel radioPlotPanel = new JPanel(new FlowLayout()); radioPlotPanel.add(newGraph); radioPlotPanel.add(existingGraph); JPanel chartOptionsPanel = new JPanel(new FlowLayout()); chartOptionsPanel.add(chartOptions); chartSelectPanel.add(radioPlotPanel); chartSelectPanel.add(chartOptionsPanel); JPanel bottomControlPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT)); bottomControlPanel.add(ok); bottomControlPanel.add(cancel); JPanel seriesNamePanel = new JPanel(new BorderLayout()); seriesNamePanel.setBorder(BorderFactory .createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Series name")); seriesNamePanel.add(seriesName, BorderLayout.CENTER); // add all the panels to the dialog dialog.add(graphTypePanel); dialog.add(functionFieldPanel); dialog.add(chartSelectPanel); dialog.add(seriesNamePanel); dialog.add(bottomControlPanel); // do all the enables and set properties radio2d.setSelected(true); newGraph.setSelected(true); chartOptions.setEnabled(false); functionField.setText("Add function expression here...."); functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15)); functionField.setForeground(Color.GRAY); seriesName.setText("New function"); ok.setMnemonic('P'); cancel.setMnemonic('C'); example.setToolTipText("click to try out"); ok.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "ok"); ok.getActionMap().put("ok", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { ok.doClick(); } }); cancel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancel"); cancel.getActionMap().put("cancel", new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { cancel.doClick(); } }); boolean found = false; for (int i = 0; i < theTabs.getTabCount(); i++) { if (theTabs.getComponentAt(i) instanceof Graph) { chartOptions.addItem(getGraphName(i)); found = true; } } if (!found) { existingGraph.setEnabled(false); chartOptions.setEnabled(false); } //add all the action listeners radio2d.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (radio2d.isSelected()) { radio3d.setSelected(false); if (chartOptions.getItemCount() > 0) { existingGraph.setEnabled(true); chartOptions.setEnabled(true); } example.setText( "<html><font size=3 color=red>Example:</font><font size=3>x/2 + 5</font></html>"); } } }); radio3d.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (radio3d.isSelected()) { radio2d.setSelected(false); newGraph.setSelected(true); existingGraph.setEnabled(false); chartOptions.setEnabled(false); example.setText("<html><font size=3 color=red>Example:</font><font size=3>x+y+5</font></html>"); } } }); newGraph.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (newGraph.isSelected()) { existingGraph.setSelected(false); chartOptions.setEnabled(false); } } }); existingGraph.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (existingGraph.isSelected()) { newGraph.setSelected(false); chartOptions.setEnabled(true); } } }); ok.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String function = functionField.getText(); Expression expr = null; try { expr = GUIPrism.getGUI().getPrism().parseSingleExpressionString(function); expr = (Expression) expr.accept(new ASTTraverseModify() { @Override public Object visit(ExpressionIdent e) throws PrismLangException { return new ExpressionConstant(e.getName(), TypeDouble.getInstance()); } }); expr.typeCheck(); expr.semanticCheck(); } catch (PrismLangException e1) { // for copying style JLabel label = new JLabel(); // html content in our case the error we want to show JEditorPane ep = new JEditorPane("text/html", "<html> There was an error parsing the function. To read about what built-in" + " functions are supported <br>and some more information on the functions, visit " + "<a href='http://www.prismmodelchecker.org/manual/ThePRISMLanguage/Expressions'>Prism expressions site</a>." + "<br><br><font color=red>Error: </font>" + e1.getMessage() + " </html>"); // handle link events ep.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { try { Desktop.getDesktop().browse(e.getURL().toURI()); } catch (IOException | URISyntaxException e1) { e1.printStackTrace(); } } } }); ep.setEditable(false); ep.setBackground(label.getBackground()); // show the error dialog JOptionPane.showMessageDialog(dialog, ep, "Parse Error", JOptionPane.ERROR_MESSAGE); return; } if (radio2d.isSelected()) { ParametricGraph graph = null; if (newGraph.isSelected()) { graph = new ParametricGraph(""); } else { for (int i = 0; i < theTabs.getComponentCount(); i++) { if (theTabs.getTitleAt(i).equals(chartOptions.getSelectedItem())) { graph = (ParametricGraph) theTabs.getComponent(i); } } } dialog.dispose(); defineConstantsAndPlot(expr, graph, seriesName.getText(), newGraph.isSelected(), true); } else if (radio3d.isSelected()) { try { expr = (Expression) expr.accept(new ASTTraverseModify() { @Override public Object visit(ExpressionIdent e) throws PrismLangException { return new ExpressionConstant(e.getName(), TypeDouble.getInstance()); } }); expr.semanticCheck(); expr.typeCheck(); } catch (PrismLangException e1) { e1.printStackTrace(); } if (expr.getAllConstants().size() < 2) { JOptionPane.showMessageDialog(dialog, "There are not enough variables in the function to plot a 3D chart!", "Error", JOptionPane.ERROR_MESSAGE); return; } // its always a new graph ParametricGraph3D graph = new ParametricGraph3D(expr); dialog.dispose(); defineConstantsAndPlot(expr, graph, seriesName.getText(), true, false); } dialog.dispose(); } }); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { dialog.dispose(); } }); // we will show info about the function when field is out of focus functionField.addFocusListener(new FocusListener() { @Override public void focusLost(FocusEvent e) { if (!functionField.getText().equals("")) { return; } functionField.setText("Add function expression here...."); functionField.setFont(new Font(Font.SANS_SERIF, Font.ITALIC, 15)); functionField.setForeground(Color.GRAY); } @Override public void focusGained(FocusEvent e) { if (!functionField.getText().equals("Add function expression here....")) { return; } functionField.setForeground(Color.BLACK); functionField.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 15)); functionField.setText(""); } }); // show the dialog dialog.setVisible(true); }
From source file:eu.cassandra.training.gui.MainGUI.java
/** * Constructor of the Training Module GUI. * //www. j av a 2s . c om * @throws UnsupportedLookAndFeelException * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException * @throws FileNotFoundException */ public MainGUI() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException, FileNotFoundException { setForeground(new Color(0, 204, 51)); // Enable the closing of the frame when pressing the x on the upper corner // of the window addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Utils.cleanFiles(); System.exit(0); } }); // Cleaning temporary files from the temp folder when starting the GUI. // Utils.cleanFiles(); // Change the platforms look and feel to Nimbus LookAndFeel lnf = new javax.swing.plaf.nimbus.NimbusLookAndFeel(); UIManager.put("NimbusLookAndFeel", Color.GREEN); UIManager.setLookAndFeel(lnf); // Setting the basic attributes of the Training Module GUI setTitle("Training Module (BETA)"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1228, 799); // Creating the menu bar and adding the menu items JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnNewMenu = new JMenu("File"); menuBar.add(mnNewMenu); JMenuItem mntmExit = new JMenuItem("Exit"); mntmExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Utils.cleanFiles(); System.exit(0); } }); mnNewMenu.add(mntmExit); JMenu mnExit = new JMenu("Help"); menuBar.add(mnExit); JMenuItem mntmManual = new JMenuItem("Manual"); mnExit.add(mntmManual); JMenuItem mntmAbout = new JMenuItem("About"); mnExit.add(mntmAbout); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); // Adding the tabbed pane to the content pane final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(tabbedPane, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 1202, Short.MAX_VALUE)); gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE, 736, GroupLayout.PREFERRED_SIZE) .addContainerGap(47, Short.MAX_VALUE))); // TABS // final JPanel importTab = new JPanel(); tabbedPane.addTab("Import Data", null, importTab, null); tabbedPane.setDisplayedMnemonicIndexAt(0, 0); tabbedPane.setEnabledAt(0, true); importTab.setLayout(null); final JPanel trainingTab = new JPanel(); tabbedPane.addTab("Train Activity Models", null, trainingTab, null); tabbedPane.setDisplayedMnemonicIndexAt(1, 1); tabbedPane.setEnabledAt(1, false); trainingTab.setLayout(null); final JPanel createResponseTab = new JPanel(); tabbedPane.addTab("Create Response Models", null, createResponseTab, null); tabbedPane.setEnabledAt(2, false); createResponseTab.setLayout(null); // RESPONSE MODEL TAB // final JPanel responseParametersPanel = new JPanel(); responseParametersPanel.setLayout(null); responseParametersPanel.setBorder( new TitledBorder(null, "Response Parameters", TitledBorder.LEADING, TitledBorder.TOP, null, null)); responseParametersPanel.setBounds(6, 6, 394, 271); createResponseTab.add(responseParametersPanel); final JPanel activityModelSelectionPanel = new JPanel(); activityModelSelectionPanel.setLayout(null); activityModelSelectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Activity Model Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null)); activityModelSelectionPanel.setBounds(6, 516, 394, 192); createResponseTab.add(activityModelSelectionPanel); final JPanel responsePanel = new JPanel(); responsePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Activity Model Change Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); responsePanel.setBounds(417, 6, 770, 385); createResponseTab.add(responsePanel); responsePanel.setLayout(new BorderLayout(0, 0)); final JPanel pricingPreviewPanel = new JPanel(); pricingPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Pricing Scheme Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); pricingPreviewPanel.setBounds(417, 438, 770, 259); createResponseTab.add(pricingPreviewPanel); pricingPreviewPanel.setLayout(new BorderLayout(0, 0)); final JPanel pricingSchemePanel = new JPanel(); pricingSchemePanel.setLayout(null); pricingSchemePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Pricing Scheme Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null)); pricingSchemePanel.setBounds(6, 274, 394, 243); createResponseTab.add(pricingSchemePanel); // ///////////////// // RESPONSE TAB // // //////////////// // RESPONSE PARAMETERS // final JLabel lblSensitivity = new JLabel("Sensitivity"); lblSensitivity.setBounds(10, 28, 78, 16); responseParametersPanel.add(lblSensitivity); final JSlider sensitivitySlider = new JSlider(); sensitivitySlider.setPaintLabels(true); sensitivitySlider.setSnapToTicks(true); sensitivitySlider.setPaintTicks(true); sensitivitySlider.setMinorTickSpacing(10); sensitivitySlider.setMajorTickSpacing(10); sensitivitySlider.setBounds(111, 28, 214, 45); responseParametersPanel.add(sensitivitySlider); final JLabel lblAwareness = new JLabel("Awareness"); lblAwareness.setBounds(10, 79, 78, 16); responseParametersPanel.add(lblAwareness); final JSlider awarenessSlider = new JSlider(); awarenessSlider.setPaintLabels(true); awarenessSlider.setPaintTicks(true); awarenessSlider.setMajorTickSpacing(10); awarenessSlider.setMinorTickSpacing(10); awarenessSlider.setSnapToTicks(true); awarenessSlider.setBounds(111, 79, 214, 45); responseParametersPanel.add(awarenessSlider); final JLabel label_7 = new JLabel("Response Model"); label_7.setBounds(10, 153, 103, 16); responseParametersPanel.add(label_7); final JRadioButton optimalCaseRadioButton = new JRadioButton("Optimal Case Scenario"); responseModelButtonGroup.add(optimalCaseRadioButton); optimalCaseRadioButton.setBounds(111, 131, 170, 18); responseParametersPanel.add(optimalCaseRadioButton); final JRadioButton normalCaseRadioButton = new JRadioButton("Normal Case Scenario"); normalCaseRadioButton.setSelected(true); responseModelButtonGroup.add(normalCaseRadioButton); normalCaseRadioButton.setBounds(111, 152, 170, 18); responseParametersPanel.add(normalCaseRadioButton); final JRadioButton discreteCaseRadioButton = new JRadioButton("Discrete Case Scenario"); discreteCaseRadioButton.setSelected(true); responseModelButtonGroup.add(discreteCaseRadioButton); discreteCaseRadioButton.setBounds(111, 173, 170, 18); responseParametersPanel.add(discreteCaseRadioButton); final JButton previewResponseButton = new JButton("Preview Response Model"); previewResponseButton.setEnabled(false); previewResponseButton.setBounds(24, 198, 157, 28); responseParametersPanel.add(previewResponseButton); final JButton createResponseButton = new JButton("Create Response Model"); createResponseButton.setEnabled(false); createResponseButton.setBounds(191, 198, 162, 28); responseParametersPanel.add(createResponseButton); final JButton createResponseAllButton = new JButton("Create Response All"); createResponseAllButton.setEnabled(false); createResponseAllButton.setBounds(111, 232, 157, 28); responseParametersPanel.add(createResponseAllButton); // SELECT ACTIVITY MODEL // final JLabel lblSelectedActivity = new JLabel("Selected Activity"); lblSelectedActivity.setBounds(10, 21, 130, 16); activityModelSelectionPanel.add(lblSelectedActivity); JScrollPane activityListScrollPane = new JScrollPane(); activityListScrollPane.setBounds(20, 39, 355, 143); activityModelSelectionPanel.add(activityListScrollPane); final JList<String> activitySelectList = new JList<String>(); activityListScrollPane.setViewportView(activitySelectList); activitySelectList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); final JButton commitButton = new JButton("Commit"); commitButton.setEnabled(false); commitButton.setBounds(151, 209, 89, 23); pricingSchemePanel.add(commitButton); JLabel lblBasicSchema = new JLabel("Basic Schema (Start-End-Value)"); lblBasicSchema.setBounds(10, 18, 182, 14); pricingSchemePanel.add(lblBasicSchema); JLabel lblNewSchemastart = new JLabel("New Schema (Start-End-Value)"); lblNewSchemastart.setBounds(197, 18, 177, 14); pricingSchemePanel.add(lblNewSchemastart); JScrollPane basicPricingSchemeScrollPane = new JScrollPane(); basicPricingSchemeScrollPane.setBounds(10, 43, 177, 161); pricingSchemePanel.add(basicPricingSchemeScrollPane); final JTextPane basicPricingSchemePane = new JTextPane(); basicPricingSchemeScrollPane.setViewportView(basicPricingSchemePane); basicPricingSchemePane.setText("00:00-23:59-0.05"); JScrollPane newPricingScrollPane = new JScrollPane(); newPricingScrollPane.setBounds(197, 43, 177, 161); pricingSchemePanel.add(newPricingScrollPane); final JTextPane newPricingSchemePane = new JTextPane(); newPricingScrollPane.setViewportView(newPricingSchemePane); JPanel buttonPanel = new JPanel(); buttonPanel.setBounds(682, 390, 265, 33); createResponseTab.add(buttonPanel); final JButton dailyResponseButton = new JButton("Daily Times"); dailyResponseButton.setEnabled(false); buttonPanel.add(dailyResponseButton); final JButton startResponseButton = new JButton("Start Time"); startResponseButton.setEnabled(false); buttonPanel.add(startResponseButton); final JPanel exportTab = new JPanel(); tabbedPane.addTab("Export Models", null, exportTab, null); tabbedPane.setEnabledAt(3, false); exportTab.setLayout(null); // PANELS // // DATA IMPORT TAB // final JPanel dataFilePanel = new JPanel(); dataFilePanel .setBorder(new TitledBorder(null, "Data File", TitledBorder.LEADING, TitledBorder.TOP, null, null)); dataFilePanel.setBounds(6, 6, 622, 284); importTab.add(dataFilePanel); dataFilePanel.setLayout(null); final JPanel disaggregationPanel = new JPanel(); disaggregationPanel.setLayout(null); disaggregationPanel.setBorder( new TitledBorder(null, "Disaggregation", TitledBorder.LEADING, TitledBorder.TOP, null, null)); disaggregationPanel.setBounds(629, 6, 567, 284); importTab.add(disaggregationPanel); final JPanel dataReviewPanel = new JPanel(); dataReviewPanel.setBorder( new TitledBorder(null, "Data Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); dataReviewPanel.setBounds(6, 293, 622, 407); importTab.add(dataReviewPanel); dataReviewPanel.setLayout(new BorderLayout(0, 0)); final JPanel consumptionModelPanel = new JPanel(); consumptionModelPanel.setBounds(629, 293, 567, 407); importTab.add(consumptionModelPanel); consumptionModelPanel.setBorder( new TitledBorder(null, "Consumption Model", TitledBorder.LEADING, TitledBorder.TOP, null, null)); consumptionModelPanel.setLayout(new BorderLayout(0, 0)); // TRAINING ACTIVITY TAB // final JPanel trainingParametersPanel = new JPanel(); trainingParametersPanel.setLayout(null); trainingParametersPanel.setBorder( new TitledBorder(null, "Training Parameters", TitledBorder.LEADING, TitledBorder.TOP, null, null)); trainingParametersPanel.setBounds(6, 6, 621, 256); trainingTab.add(trainingParametersPanel); final JPanel applianceSelectionPanel = new JPanel(); applianceSelectionPanel.setLayout(null); applianceSelectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Appliance/Activity Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null)); applianceSelectionPanel.setBounds(630, 6, 557, 256); trainingTab.add(applianceSelectionPanel); final JPanel expectedPowerPanel = new JPanel(); expectedPowerPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Expected Power Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); expectedPowerPanel.setBounds(630, 261, 557, 447); trainingTab.add(expectedPowerPanel); expectedPowerPanel.setLayout(new BorderLayout(0, 0)); contentPane.setLayout(gl_contentPane); // EXPORT TAB // JPanel modelExportPanel = new JPanel(); modelExportPanel.setLayout(null); modelExportPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Model Export Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null)); modelExportPanel.setBounds(10, 11, 596, 267); exportTab.add(modelExportPanel); final JPanel exportPreviewPanel = new JPanel(); exportPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Export Model Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); exportPreviewPanel.setBounds(10, 310, 1187, 387); exportTab.add(exportPreviewPanel); exportPreviewPanel.setLayout(new BorderLayout(0, 0)); JPanel exportButtonsPanel = new JPanel(); exportButtonsPanel.setBounds(322, 279, 536, 33); exportTab.add(exportButtonsPanel); JPanel connectionPanel = new JPanel(); connectionPanel.setLayout(null); connectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Connection Properties", TitledBorder.LEADING, TitledBorder.TOP, null, null)); connectionPanel.setBounds(606, 11, 581, 267); exportTab.add(connectionPanel); // COMPONENTS // // IMPORT TAB // // DATA IMPORT // final JLabel lblSource = new JLabel("Data Source:"); lblSource.setBounds(23, 47, 71, 16); dataFilePanel.add(lblSource); final JTextField pathField = new JTextField(); pathField.setEditable(false); pathField.setBounds(99, 41, 405, 28); dataFilePanel.add(pathField); pathField.setColumns(10); final JButton dataBrowseButton = new JButton("Browse"); dataBrowseButton.setBounds(516, 41, 87, 28); dataFilePanel.add(dataBrowseButton); final JButton resetButton = new JButton("Reset"); resetButton.setBounds(516, 81, 87, 28); dataFilePanel.add(resetButton); final JLabel lblDataMeasurementsFrom = new JLabel("Data Measurements From:"); lblDataMeasurementsFrom.setBounds(23, 90, 154, 16); dataFilePanel.add(lblDataMeasurementsFrom); final JRadioButton singleApplianceRadioButton = new JRadioButton("Single Appliance"); singleApplianceRadioButton.setEnabled(false); dataMeasurementsButtonGroup.add(singleApplianceRadioButton); singleApplianceRadioButton.setBounds(242, 110, 115, 18); dataFilePanel.add(singleApplianceRadioButton); final JRadioButton installationRadioButton = new JRadioButton("Installation"); installationRadioButton.setSelected(true); installationRadioButton.setEnabled(false); dataMeasurementsButtonGroup.add(installationRadioButton); installationRadioButton.setBounds(242, 89, 115, 18); dataFilePanel.add(installationRadioButton); final JLabel labelConsumptionModel = new JLabel("Consumption Model:"); labelConsumptionModel.setBounds(23, 179, 120, 16); dataFilePanel.add(labelConsumptionModel); final JButton importDataButton = new JButton("Import Data"); importDataButton.setEnabled(false); importDataButton.setBounds(23, 237, 126, 28); dataFilePanel.add(importDataButton); final JButton disaggregateButton = new JButton("Disaggregate"); disaggregateButton.setEnabled(false); disaggregateButton.setBounds(216, 237, 147, 28); dataFilePanel.add(disaggregateButton); final JButton createEventsButton = new JButton("Create Events Dataset"); createEventsButton.setEnabled(false); createEventsButton.setBounds(422, 237, 181, 28); dataFilePanel.add(createEventsButton); final JTextField consumptionPathField = new JTextField(); consumptionPathField.setEnabled(false); consumptionPathField.setEditable(false); consumptionPathField.setColumns(10); consumptionPathField.setBounds(99, 197, 405, 28); dataFilePanel.add(consumptionPathField); final JButton consumptionBrowseButton = new JButton("Browse"); consumptionBrowseButton.setEnabled(false); consumptionBrowseButton.setBounds(516, 197, 87, 28); dataFilePanel.add(consumptionBrowseButton); JLabel lblTypeOfMeasurements = new JLabel("Type of Measurements"); lblTypeOfMeasurements.setBounds(23, 141, 154, 16); dataFilePanel.add(lblTypeOfMeasurements); final JRadioButton activePowerRadioButton = new JRadioButton("Active Power (P)"); powerButtonGroup.add(activePowerRadioButton); activePowerRadioButton.setEnabled(false); activePowerRadioButton.setBounds(242, 140, 115, 18); dataFilePanel.add(activePowerRadioButton); final JRadioButton activeAndReactivePowerRadioButton = new JRadioButton("Active and Reactive Power (P, Q)"); activeAndReactivePowerRadioButton.setSelected(true); powerButtonGroup.add(activeAndReactivePowerRadioButton); activeAndReactivePowerRadioButton.setEnabled(false); activeAndReactivePowerRadioButton.setBounds(242, 161, 262, 18); dataFilePanel.add(activeAndReactivePowerRadioButton); // ////////////////// // DISAGGREGATION // // ///////////////// final JLabel lblAppliancesDetected = new JLabel("Detected Appliances "); lblAppliancesDetected.setBounds(18, 33, 130, 16); disaggregationPanel.add(lblAppliancesDetected); JScrollPane scrollPane_2 = new JScrollPane(); scrollPane_2.setBounds(145, 31, 396, 231); disaggregationPanel.add(scrollPane_2); final JList<String> detectedApplianceList = new JList<String>(); scrollPane_2.setViewportView(detectedApplianceList); detectedApplianceList.setEnabled(false); detectedApplianceList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); // //////////////// // TRAINING TAB // // //////////////// // TRAINING PARAMETERS // final JLabel label_1 = new JLabel("Times Per Day"); label_1.setBounds(19, 40, 103, 16); trainingParametersPanel.add(label_1); final JRadioButton timesHistogramRadioButton = new JRadioButton("Histogram"); timesHistogramRadioButton.setSelected(true); timesDailyButtonGroup.add(timesHistogramRadioButton); timesHistogramRadioButton.setBounds(160, 38, 87, 18); trainingParametersPanel.add(timesHistogramRadioButton); final JRadioButton timesNormalRadioButton = new JRadioButton("Normal Distribution"); timesNormalRadioButton.setEnabled(false); timesDailyButtonGroup.add(timesNormalRadioButton); timesNormalRadioButton.setBounds(304, 40, 137, 18); trainingParametersPanel.add(timesNormalRadioButton); JRadioButton timesGaussianRadioButton = new JRadioButton("Gaussian Mixture"); timesGaussianRadioButton.setEnabled(false); timesDailyButtonGroup.add(timesGaussianRadioButton); timesGaussianRadioButton.setBounds(478, 38, 137, 18); trainingParametersPanel.add(timesGaussianRadioButton); final JLabel label_2 = new JLabel("Start Time"); label_2.setBounds(19, 133, 103, 16); trainingParametersPanel.add(label_2); final JRadioButton startHistogramRadioButton = new JRadioButton("Histogram"); startHistogramRadioButton.setSelected(true); startTimeButtonGroup.add(startHistogramRadioButton); startHistogramRadioButton.setBounds(160, 131, 87, 18); trainingParametersPanel.add(startHistogramRadioButton); final JRadioButton startNormalRadioButton = new JRadioButton("Normal Distribution"); // startNormalRadioButton.setEnabled(false); startTimeButtonGroup.add(startNormalRadioButton); startNormalRadioButton.setBounds(304, 133, 137, 18); trainingParametersPanel.add(startNormalRadioButton); final JRadioButton startGaussianRadioButton = new JRadioButton("Gaussian Mixture"); startGaussianRadioButton.setSelected(true); startTimeButtonGroup.add(startGaussianRadioButton); startGaussianRadioButton.setBounds(478, 131, 137, 18); trainingParametersPanel.add(startGaussianRadioButton); final JLabel label_3 = new JLabel("Duration"); label_3.setBounds(19, 86, 103, 16); trainingParametersPanel.add(label_3); final JRadioButton durationHistogramRadioButton = new JRadioButton("Histogram"); durationHistogramRadioButton.setSelected(true); durationButtonGroup.add(durationHistogramRadioButton); durationHistogramRadioButton.setBounds(160, 84, 87, 18); trainingParametersPanel.add(durationHistogramRadioButton); final JRadioButton durationNormalRadioButton = new JRadioButton("Normal Distribution"); durationNormalRadioButton.setSelected(true); durationButtonGroup.add(durationNormalRadioButton); durationNormalRadioButton.setBounds(304, 86, 137, 18); trainingParametersPanel.add(durationNormalRadioButton); final JRadioButton durationGaussianRadioButton = new JRadioButton("Gaussian Mixture"); durationButtonGroup.add(durationGaussianRadioButton); durationGaussianRadioButton.setBounds(478, 84, 137, 18); trainingParametersPanel.add(durationGaussianRadioButton); final JButton trainingButton = new JButton("Train"); trainingButton.setBounds(125, 194, 115, 28); trainingParametersPanel.add(trainingButton); final JButton trainAllButton = new JButton("Train All"); trainAllButton.setBounds(366, 194, 115, 28); trainingParametersPanel.add(trainAllButton); // APPLIANCE SELECTION // final JLabel label_4 = new JLabel("Selected Appliance"); label_4.setBounds(18, 33, 130, 16); applianceSelectionPanel.add(label_4); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(128, 29, 419, 216); applianceSelectionPanel.add(scrollPane_1); final JList<String> selectedApplianceList = new JList<String>(); scrollPane_1.setViewportView(selectedApplianceList); selectedApplianceList.setEnabled(false); selectedApplianceList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); // DISTRIBUTION SELECTION // JPanel distributionSelectionPanel = new JPanel(); distributionSelectionPanel.setBounds(80, 261, 482, 33); trainingTab.add(distributionSelectionPanel); final JButton dailyTimesButton = new JButton("Daily Times"); dailyTimesButton.setEnabled(false); distributionSelectionPanel.add(dailyTimesButton); final JButton durationButton = new JButton("Duration"); durationButton.setEnabled(false); distributionSelectionPanel.add(durationButton); final JButton startTimeButton = new JButton("Start Time"); startTimeButton.setEnabled(false); distributionSelectionPanel.add(startTimeButton); final JButton startTimeBinnedButton = new JButton("Start Time Binned"); startTimeBinnedButton.setEnabled(false); distributionSelectionPanel.add(startTimeBinnedButton); final JPanel distributionPreviewPanel = new JPanel(); distributionPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Distribution Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); distributionPreviewPanel.setBounds(6, 299, 621, 409); trainingTab.add(distributionPreviewPanel); distributionPreviewPanel.setLayout(new BorderLayout(0, 0)); // ////////////////// // EXPORT TAB /////// // ///////////////// JLabel exportModelLabel = new JLabel("Select Model"); exportModelLabel.setBounds(10, 34, 151, 16); modelExportPanel.add(exportModelLabel); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(83, 32, 503, 212); modelExportPanel.add(scrollPane); final JList<String> exportModelList = new JList<String>(); scrollPane.setViewportView(exportModelList); exportModelList.setEnabled(false); exportModelList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); // EXPORT TAB // final JButton exportDailyButton = new JButton("Daily Times"); exportDailyButton.setEnabled(false); exportButtonsPanel.add(exportDailyButton); final JButton exportDurationButton = new JButton("Duration"); exportDurationButton.setEnabled(false); exportButtonsPanel.add(exportDurationButton); final JButton exportStartButton = new JButton("Start Time"); exportStartButton.setEnabled(false); exportButtonsPanel.add(exportStartButton); final JButton exportStartBinnedButton = new JButton("Start Time Binned"); exportStartBinnedButton.setEnabled(false); exportButtonsPanel.add(exportStartBinnedButton); final JButton exportExpectedPowerButton = new JButton("Expected Power"); exportExpectedPowerButton.setEnabled(false); exportButtonsPanel.add(exportExpectedPowerButton); JLabel usernameLabel = new JLabel("Username:"); usernameLabel.setBounds(46, 27, 71, 16); connectionPanel.add(usernameLabel); final JTextField usernameTextField; usernameTextField = new JTextField(); usernameTextField.setText("user"); usernameTextField.setColumns(10); usernameTextField.setBounds(122, 21, 405, 28); connectionPanel.add(usernameTextField); final JButton exportButton = new JButton("Export Entity"); exportButton.setEnabled(false); exportButton.setBounds(46, 178, 147, 28); connectionPanel.add(exportButton); final JButton exportAllBaseButton = new JButton("Export All Base"); exportAllBaseButton.setEnabled(false); exportAllBaseButton.setBounds(203, 178, 177, 28); connectionPanel.add(exportAllBaseButton); final JButton exportAllResponseButton = new JButton("Export All Response"); exportAllResponseButton.setEnabled(false); exportAllResponseButton.setBounds(390, 178, 181, 28); connectionPanel.add(exportAllResponseButton); JLabel passwordLabel = new JLabel("Password:"); passwordLabel.setBounds(46, 62, 71, 16); connectionPanel.add(passwordLabel); JLabel UrlLabel = new JLabel("URL:"); UrlLabel.setBounds(46, 105, 71, 16); connectionPanel.add(UrlLabel); final JTextField urlTextField; urlTextField = new JTextField(); urlTextField.setText("https://160.40.50.233:8443/cassandra/api"); urlTextField.setColumns(10); urlTextField.setBounds(122, 99, 405, 28); connectionPanel.add(urlTextField); final JButton connectButton = new JButton("Connect"); connectButton.setEnabled(false); connectButton.setBounds(217, 138, 147, 28); connectionPanel.add(connectButton); final JPasswordField passwordField; passwordField = new JPasswordField(); passwordField.setBounds(122, 60, 405, 28); connectionPanel.add(passwordField); final JTextField householdNameTextField; householdNameTextField = new JTextField(); householdNameTextField.setEnabled(false); householdNameTextField.setBounds(166, 225, 405, 31); connectionPanel.add(householdNameTextField); householdNameTextField.setColumns(10); final JLabel householdNameLabel = new JLabel("Export Household Name:"); householdNameLabel.setBounds(24, 233, 147, 14); connectionPanel.add(householdNameLabel); JButton btnOpenPlatform = new JButton("Open Platform"); btnOpenPlatform.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { Desktop.getDesktop() .browse(new URL("https://cassandra.iti.gr:8443/cassandra/app.html").toURI()); } catch (Exception e) { e.printStackTrace(); } } }); btnOpenPlatform.setBounds(401, 138, 147, 28); connectionPanel.add(btnOpenPlatform); // ////////////////// // ACTIONS /////// // ///////////////// // IMPORT TAB // // DATA IMPORT //// dataBrowseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the browse button to * input the data file on the Data File panel of the Import Data tab. * */ @Override public void actionPerformed(ActionEvent e) { // Opens the browse panel to find the data set file JFileChooser fc = new JFileChooser("./"); // Adds a filter to the type of files acceptable for selection fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileFilter(new MyFilter2()); int returnVal = fc.showOpenDialog(contentPane); // After choosing the file some of the options in the Data File panel // are unlocked if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); pathField.setText(file.getAbsolutePath()); importDataButton.setEnabled(true); activePowerRadioButton.setEnabled(true); activeAndReactivePowerRadioButton.setEnabled(true); installationRadioButton.setEnabled(true); singleApplianceRadioButton.setEnabled(true); } } }); consumptionBrowseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the browse button to * input the consumption model file on the Data File panel of the Import * Data tab. * */ @Override public void actionPerformed(ActionEvent e) { // Opens the browse panel to find the consumption model file JFileChooser fc = new JFileChooser("./"); // Adds a filter to the type of files acceptable for selection fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileFilter(new MyFilter()); int returnVal = fc.showOpenDialog(contentPane); // After choosing the file some of the options in the Data File panel // are unlocked if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); consumptionPathField.setText(file.getAbsolutePath()); createEventsButton.setEnabled(true); } } }); resetButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the reset button * on the Data File panel of the Import Data tab. All the imported and * created entities are removed and the Training Module goes back to its * initial state. * */ @Override public void actionPerformed(ActionEvent e) { // Cleaning the Import Data tab components pathField.setText(""); consumptionPathField.setText(""); importDataButton.setEnabled(false); disaggregateButton.setEnabled(false); createEventsButton.setEnabled(false); installation = new Installation(); dataBrowseButton.setEnabled(true); consumptionBrowseButton.setEnabled(false); installationRadioButton.setEnabled(false); installationRadioButton.setSelected(true); singleApplianceRadioButton.setEnabled(false); activePowerRadioButton.setEnabled(false); activeAndReactivePowerRadioButton.setEnabled(false); activeAndReactivePowerRadioButton.setSelected(true); dataReviewPanel.removeAll(); dataReviewPanel.updateUI(); consumptionModelPanel.removeAll(); consumptionModelPanel.updateUI(); detectedApplianceList.setSelectedIndex(-1); detectedAppliances.clear(); detectedApplianceList.setListData(new String[0]); detectedApplianceList.repaint(); // Cleaning the Training Activity Models tab components distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); expectedPowerPanel.removeAll(); expectedPowerPanel.updateUI(); selectedApplianceList.setSelectedIndex(-1); selectedAppliances.clear(); selectedApplianceList.setListData(new String[0]); selectedApplianceList.repaint(); timesHistogramRadioButton.setSelected(true); durationNormalRadioButton.setSelected(true); startGaussianRadioButton.setSelected(true); // Cleaning the Create Response Models tab components sensitivitySlider.setValue(50); awarenessSlider.setValue(50); normalCaseRadioButton.setSelected(true); previewResponseButton.setEnabled(false); createResponseButton.setEnabled(false); createResponseAllButton.setEnabled(false); pricingPreviewPanel.removeAll(); pricingPreviewPanel.updateUI(); responsePanel.removeAll(); responsePanel.updateUI(); activitySelectList.setSelectedIndex(-1); activityModels.clear(); activitySelectList.setListData(new String[0]); activitySelectList.repaint(); basicPricingSchemePane.setText("00:00-23:59-0.05"); newPricingSchemePane.setText(""); commitButton.setEnabled(false); dailyResponseButton.setEnabled(false); startResponseButton.setEnabled(false); // Cleaning the Export Models tab components exportModelList.setSelectedIndex(-1); exportModels.clear(); exportModelList.setListData(new String[0]); exportModelList.repaint(); exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); exportDailyButton.setEnabled(false); exportDurationButton.setEnabled(false); exportStartButton.setEnabled(false); exportStartBinnedButton.setEnabled(false); exportExpectedPowerButton.setEnabled(false); exportButton.setEnabled(false); exportAllBaseButton.setEnabled(false); exportAllResponseButton.setEnabled(false); householdNameTextField.setEnabled(false); // Disabling the necessary tabs tabbedPane.setEnabledAt(1, false); tabbedPane.setEnabledAt(2, false); tabbedPane.setEnabledAt(3, false); // Clearing the arrayList in need tempAppliances.clear(); tempActivities.clear(); // Removing temporary files Utils.cleanFiles(); trained = false; } }); singleApplianceRadioButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Single Appliance * radio button on the Data File panel of the Import Data tab. */ @Override public void actionPerformed(ActionEvent e) { consumptionPathField.setEnabled(false); consumptionBrowseButton.setEnabled(false); consumptionPathField.setText(""); } }); installationRadioButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Installation * radio button on the Data File panel of the Import Data tab. */ @Override public void actionPerformed(ActionEvent e) { consumptionPathField.setEnabled(false); consumptionBrowseButton.setEnabled(false); consumptionPathField.setText(""); } }); importDataButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Import Data * button on the Data File panel of the Import Data tab. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Change the state of some components installationRadioButton.setEnabled(false); singleApplianceRadioButton.setEnabled(false); importDataButton.setEnabled(false); dataBrowseButton.setEnabled(false); activePowerRadioButton.setEnabled(false); activeAndReactivePowerRadioButton.setEnabled(false); // Check if both active and reactive activeOnly data set are available boolean power = activePowerRadioButton.isSelected(); int parse = -1; // Parsing the measurements file try { parse = Utils.parseMeasurementsFile(pathField.getText(), power); } catch (IOException e2) { e2.printStackTrace(); } // If everything is OK if (parse == -1) { try { // Creating new installation installation = new Installation(pathField.getText(), power); } catch (IOException e2) { e2.printStackTrace(); } // Show the measurements in the preview chart ChartPanel chartPanel = null; try { chartPanel = installation.measurementsChart(); } catch (IOException e1) { e1.printStackTrace(); } dataReviewPanel.add(chartPanel, BorderLayout.CENTER); dataReviewPanel.validate(); disaggregateButton.setEnabled(false); createEventsButton.setEnabled(false); // Enable the appropriate buttons given source of measurements if (installationRadioButton.isSelected()) { disaggregateButton.setEnabled(true); } else if (singleApplianceRadioButton.isSelected()) { consumptionPathField.setEnabled(true); consumptionBrowseButton.setEnabled(true); } // Add installation to the export models list exportModels.addElement(installation.toString()); exportModels.addElement(installation.getPerson().getName()); householdNameTextField.setText(installation.getName()); // Enable Export Models tab exportModelList.setEnabled(true); exportModelList.setModel(exportModels); tabbedPane.setEnabledAt(3, true); } // In case of an error during the measurement parsing show the line of // error and reset settings. else { JFrame error = new JFrame(); JOptionPane.showMessageDialog(error, "Parsing measurements file failed. The problem seems to be in line " + parse + ".Check the selected buttons and the file provided and try again.", "Inane error", JOptionPane.ERROR_MESSAGE); resetButton.doClick(); } } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); disaggregateButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Disaggregate * button on the Data File panel of the Import Data tab in order to * automatically analyse the data set and extract the appliances and * activities within. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Get auxiliary files containing appliances and activities which are // the output of the disaggregation process. String filename = pathField.getText(); File file = new File(filename); String folder = file.getParent() + "/"; String fileNameWithExtension = file.getName(); String fileName = file.getName().substring(0, file.getName().length() - 4); filename = pathField.getText().substring(0, pathField.getText().length() - 4); File appliancesFile = new File(Constants.resultFolder + fileName + "ApplianceList.csv"); File activitiesFile = new File(Constants.resultFolder + fileName + "ActivityList.csv"); if ((Constants.USE_FILES == false) || (!appliancesFile.exists() && !activitiesFile.exists())) { try { System.out.println("IN!!!"); Disaggregate dis = new Disaggregate(folder, fileNameWithExtension); appliancesFile = new File(Constants.resultFolder + fileName + "ApplianceList.csv"); activitiesFile = new File(Constants.resultFolder + fileName + "ActivityList.csv"); } catch (Exception e2) { System.out.println("Missing File"); e2.printStackTrace(); } } // If these exist, disaggregation was successful and the procedure can // continue if (appliancesFile.exists() && activitiesFile.exists()) { // Read appliance file and start appliance parsing Scanner input = null; try { input = new Scanner(appliancesFile); } catch (FileNotFoundException e1) { e1.printStackTrace(); } String nextLine; String[] line; while (input.hasNext()) { nextLine = input.nextLine(); line = nextLine.split(","); String name = line[1] + " " + line[0]; // String activity = line[1]; String activity = name; String[] temp = line[0].split(" "); String type = ""; if (temp.length == 1) type = temp[0]; else { for (int i = 0; i < temp.length - 1; i++) type += temp[i] + " "; type = type.trim(); } boolean refFlag = activity.contains("Refrigeration"); boolean wmFlag = name.contains("Washing"); double p = 0, q = 0; int distance = 0, duration = 0; if (refFlag) { p = Double.parseDouble(line[2]); q = Double.parseDouble(line[3]); duration = Integer.parseInt(line[4]); distance = Integer.parseInt(line[5]); // For each appliance found in the file, an temporary Appliance // Entity is created. tempAppliances.add(new ApplianceTemp(name, installation.getName(), type, activity, p, q, duration, distance)); } else if (wmFlag) { double[] pValues = new double[line.length / 2 - 1]; double[] qValues = new double[line.length / 2 - 1]; // For each appliance found in the file, an temporary Appliance // Entity is created. for (int i = 0; i < pValues.length; i++) { pValues[i] = Double.parseDouble(line[2 + 2 * i]); qValues[i] = Double.parseDouble(line[3 + 2 * i]); } tempAppliances.add(new ApplianceTemp(name, installation.getName(), type, activity, pValues, qValues)); } else { p = Double.parseDouble(line[2]); q = Double.parseDouble(line[3]); // For each appliance found in the file, an temporary Appliance // Entity is created. tempAppliances .add(new ApplianceTemp(name, installation.getName(), type, activity, p, q)); } } System.out.println("Appliances:" + tempAppliances.size()); input.close(); // Read activity file and start activity parsing try { input = new Scanner(activitiesFile); } catch (FileNotFoundException e1) { System.out.println("Problem with activity file."); e1.printStackTrace(); } while (input.hasNext()) { nextLine = input.nextLine(); line = nextLine.split(","); // System.out.println(Arrays.toString(line)); // String name = line[0]; // String activity = line[1]; String activity = line[1] + " " + line[0]; String type = line[1]; int start = Integer.parseInt(line[2]); int end = Integer.parseInt(line[3]); // Search for existing activity int activityIndex = findActivity(activity); // if not found, create a new one if (activityIndex == -1) { // System.out.println("In!"); ActivityTemp newActivity = new ActivityTemp(activity, type); newActivity.addEvent(start, end); tempActivities.add(newActivity); // System.out.println(tempActivities.toString()); } // else add data to the found activity else tempActivities.get(activityIndex).addEvent(start, end); } // This is hard copied for now ArrayList<ActivityTemp> activities = findAllActivity("Refrigeration"); for (ActivityTemp activityTemp : activities) { tempActivities.remove(activityTemp); System.out.println("Refrigeration Removed"); } int index = findActivity("Standby"); if (index != -1) { tempActivities.remove(index); System.out.println("Standby Consumption Removed"); } // TODO Add these lines in case we want to remove activities with // small sampling number // System.out.println(tempActivities.size()); // for (int i = tempActivities.size() - 1; i >= 0; i--) // if (tempActivities.get(i).getEvents().size() < threshold) // tempActivities.remove(i); // Create an event file for each activity, in order to be able to // use // it for training the behaviour models if asked from the user for (int i = 0; i < tempActivities.size(); i++) { // tempActivities.get(i).status(); try { tempActivities.get(i).createEventFile(); } catch (IOException e1) { System.out.println("Problem with creating events file."); e1.printStackTrace(); } } input.close(); // Add each found appliance (after converting temporary appliance to // normal appliance) in the installation Entity, to the detected // appliance and export models list for (ApplianceTemp temp : tempAppliances) { Appliance tempAppliance = temp.toAppliance(); installation.addAppliance(tempAppliance); detectedAppliances.addElement(tempAppliance.toString()); exportModels.addElement(tempAppliance.toString()); } // Add appliances corresponding to each activity, remove activities // without appliances and add activities to the selected activities // list. for (int i = tempActivities.size() - 1; i >= 0; i--) { tempActivities.get(i).setAppliances(findAppliances(tempActivities.get(i))); if (tempActivities.get(i).getAppliances().size() == 0) { tempActivities.remove(i); } else selectedAppliances.addElement(tempActivities.get(i).toString()); } } // In case of an error. else { int temp = 8 + ((int) (Math.random() * 2)); for (int i = 0; i < temp; i++) { String name = "Appliance " + i; String powerModel = ""; String reactiveModel = ""; int tempIndex = i % 5; switch (tempIndex) { case 0: powerModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"p\":1900,\"d\":1,\"s\":0}]},{\"n\":0,\"values\":[{\"p\":300,\"d\":1,\"s\":0}]}]}"; reactiveModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"q\":-40,\"d\":1,\"s\":0}]},{\"n\":0,\"values\":[{\"q\":-10,\"d\":1,\"s\":0}]}]}"; break; case 1: powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 140.0, \"d\" : 20, \"s\": 0.0}]}]}"; reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : 120.0, \"d\" : 20, \"s\": 0.0}]}]}"; break; case 2: powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 95.0, \"d\" : 20, \"s\": 0.0}, {\"p\" :80.0, \"d\" : 18, \"s\": 0.0}, {\"p\" : 0.0, \"d\" : 73, \"s\": 0.0}]}]}]}"; reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : 0.0, \"d\" : 20, \"s\": 0.0}, {\"q\" : 0.0, \"d\" : 18, \"s\": 0.0}, {\"q\" : 0.0, \"d\" : 73, \"s\": 0.0}]}]}]}"; break; case 3: powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 30.0, \"d\" : 20, \"s\": 0.0}]}]}"; reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : -5.0, \"d\" : 20, \"s\": 0.0}]}]}"; break; case 4: powerModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"p\":150,\"d\":25,\"s\":0},{\"p\":2000,\"d\":13,\"s\":0},{\"p\":100,\"d\":62,\"s\":0}]}]}"; reactiveModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"q\":400,\"d\":25,\"s\":0},{\"q\":200,\"d\":13,\"s\":0},{\"q\":300,\"d\":62,\"s\":0}]}]}"; break; } Appliance tempAppliance = new Appliance(name, installation.getName(), powerModel, reactiveModel, "Demo/eventsAll" + tempIndex + ".csv"); installation.addAppliance(tempAppliance); detectedAppliances.addElement(tempAppliance.toString()); selectedAppliances.addElement(tempAppliance.toString()); exportModels.addElement(tempAppliance.toString()); } } // Enable all appliance/activity lists detectedApplianceList.setEnabled(true); detectedApplianceList.setModel(detectedAppliances); detectedApplianceList.setSelectedIndex(0); tabbedPane.setEnabledAt(1, true); selectedApplianceList.setEnabled(true); selectedApplianceList.setModel(selectedAppliances); // exportModelList.setEnabled(true); // exportModelList.setModel(exportModels); // tabbedPane.setEnabledAt(3, true); // Disable unnecessary buttons. disaggregateButton.setEnabled(false); createEventsButton.setEnabled(false); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); createEventsButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Create Events * button on the Data File panel of the Import Data tab. This button is * used when there is a single appliance with an known consumption model * so that the events can be extracted automatically from the data set. * Used for presentation purposes only since is depricated by the * disaggregation function. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Parse the consumption model file File file = new File(consumptionPathField.getText()); String temp = file.getName(); temp = temp.replace(".", " "); String name = temp.split(" ")[0]; Appliance appliance = null; try { int rand = (int) (Math.random() * 5); appliance = new Appliance(name, consumptionPathField.getText(), consumptionPathField.getText(), "Demo/eventsAll" + rand + ".csv", installation, activePowerRadioButton.isSelected()); } catch (IOException e1) { e1.printStackTrace(); } // Add appliance to the installation entity installation.addAppliance(appliance); // Enable all appliance/activity lists detectedAppliances.addElement(appliance.toString()); selectedAppliances.addElement(appliance.toString()); exportModels.addElement(appliance.toString()); detectedApplianceList.setEnabled(true); detectedApplianceList.setModel(detectedAppliances); detectedApplianceList.setSelectedIndex(0); tabbedPane.setEnabledAt(1, true); selectedApplianceList.setEnabled(true); selectedApplianceList.setModel(selectedAppliances); // exportModelList.setEnabled(true); // exportModelList.setModel(exportModels); // tabbedPane.setEnabledAt(3, true); // Disable unnecessary buttons. disaggregateButton.setEnabled(false); createEventsButton.setEnabled(false); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); // APPLIANCE DETECTION // detectedApplianceList.addListSelectionListener(new ListSelectionListener() { /** * This function is called when the user selects an appliance from the * list of Detected Appliances on the Disaggregation panel of the Import * Data tab. Then the corresponding consumption model is presented in the * Consumption Model Preview panel. */ @Override public void valueChanged(ListSelectionEvent e) { consumptionModelPanel.removeAll(); consumptionModelPanel.updateUI(); if (detectedAppliances.size() >= 1) { String selection = detectedApplianceList.getSelectedValue(); Appliance current = installation.findAppliance(selection); ChartPanel chartPanel = current.consumptionGraph(); consumptionModelPanel.add(chartPanel, BorderLayout.CENTER); consumptionModelPanel.validate(); } } }); // // TRAINING TAB // trainingTab.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent arg0) { selectedApplianceList.setSelectedIndex(0); } }); trainingButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Train button on * the Training Parameters panel of the Train Activity Models tab. It * contains the procedure needed to create an activity model based on the * event set of the appliance or activity. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); responsePanel.removeAll(); responsePanel.validate(); pricingPreviewPanel.removeAll(); pricingPreviewPanel.validate(); previewResponseButton.setEnabled(false); createResponseButton.setEnabled(false); createResponseAllButton.setEnabled(false); dailyResponseButton.setEnabled(false); startResponseButton.setEnabled(false); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Searching for existing activity or appliance. String selection = selectedApplianceList.getSelectedValue(); ActivityTemp activity = null; if (tempActivities.size() > 0) activity = tempActivities.get(findActivity(selection)); Appliance current = installation.findAppliance(selection); String startTime, duration, dailyTimes; // Check for the selected distribution methods for training. if (timesHistogramRadioButton.isSelected()) dailyTimes = "Histogram"; else if (timesNormalRadioButton.isSelected()) dailyTimes = "Normal"; else dailyTimes = "GMM"; if (durationHistogramRadioButton.isSelected()) duration = "Histogram"; else if (durationNormalRadioButton.isSelected()) duration = "Normal"; else duration = "GMM"; if (startHistogramRadioButton.isSelected()) startTime = "Histogram"; else if (startNormalRadioButton.isSelected()) startTime = "Normal"; else startTime = "GMM"; String[] distributions = { dailyTimes, duration, startTime, "Histogram" }; // If the selected object from the list is an appliance the training // procedure for the appliance begins. if (activity == null) { try { installation.getPerson().train(current, distributions); } catch (IOException e1) { e1.printStackTrace(); } } // If the selected object from the list is an activity the training // procedure for the activity begins. else { try { installation.getPerson().train(activity, distributions); } catch (IOException e1) { e1.printStackTrace(); } } // System.out.println("Training OK!"); distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); expectedPowerPanel.removeAll(); expectedPowerPanel.updateUI(); // Show the distribution created on the Distribution Preview Panel ActivityModel activityModel = installation.getPerson().findActivity(selection, true); if (activityModel == null) activityModel = installation.getPerson().findActivity(current); ChartPanel chartPanel = activityModel.createDailyTimesDistributionChart(); distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER); distributionPreviewPanel.validate(); chartPanel = activityModel.createExpectedPowerChart(); expectedPowerPanel.add(chartPanel, BorderLayout.CENTER); expectedPowerPanel.validate(); // Add the Activity model to the list of trained Activity models of // the Create Response Models tab int size = activitySelectList.getModel().getSize(); if (size > 0) { activityModels = (DefaultListModel<String>) activitySelectList.getModel(); if (activityModels.contains(activityModel.getName()) == false) activityModels.addElement(activityModel.getName()); } else { activityModels = new DefaultListModel<String>(); activityModels.addElement(activityModel.getName()); activitySelectList.setEnabled(true); } activitySelectList.setModel(activityModels); // Add the trained model to the export list also. size = exportModelList.getModel().getSize(); if (size > 0) { exportModels = (DefaultListModel<String>) exportModelList.getModel(); if (exportModels.contains(activityModel.getName()) == false) exportModels.addElement(activityModel.getName()); } else { exportModels = new DefaultListModel<String>(); exportModels.addElement(activityModel.getName()); exportModelList.setEnabled(true); } // Enable some buttons necessary to show the results. dailyTimesButton.setEnabled(true); durationButton.setEnabled(true); startTimeButton.setEnabled(true); startTimeBinnedButton.setEnabled(true); exportModelList.setModel(exportModels); exportDailyButton.setEnabled(true); exportDurationButton.setEnabled(true); exportStartButton.setEnabled(true); exportStartBinnedButton.setEnabled(true); tabbedPane.setEnabledAt(2, true); } finally { root.setCursor(Cursor.getDefaultCursor()); trained = true; } } }); trainAllButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Train All button on * the Training Parameters panel of the Train Activity Models tab. It * is iterating the aforementioned training procedure to each of the * objects on the list. */ @Override public void actionPerformed(ActionEvent e) { responsePanel.removeAll(); responsePanel.validate(); pricingPreviewPanel.removeAll(); pricingPreviewPanel.validate(); previewResponseButton.setEnabled(false); createResponseButton.setEnabled(false); createResponseAllButton.setEnabled(false); dailyResponseButton.setEnabled(false); startResponseButton.setEnabled(false); for (int i = 0; i < selectedApplianceList.getModel().getSize(); i++) { selectedApplianceList.setSelectedIndex(i); trainingButton.doClick(); } } }); dailyTimesButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Daily Times button on * the Distribution Preview panel of the Train Activity Models tab. It * shows the Daily Times Distribution for the selected object from the * list if available. */ @Override public void actionPerformed(ActionEvent arg0) { distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); String selection = selectedApplianceList.getSelectedValue(); Appliance current = installation.findAppliance(selection); ActivityModel activityModel = installation.getPerson().findActivity(selection, true); if (activityModel == null) activityModel = installation.getPerson().findActivity(current); ChartPanel chartPanel = activityModel.createDailyTimesDistributionChart(); distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER); distributionPreviewPanel.validate(); } }); startTimeBinnedButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Start Time Binned * button on the Distribution Preview panel of the Train Activity * Models tab. It shows the Start Time Binned Distribution for the * selected object from the list if available. */ @Override public void actionPerformed(ActionEvent arg0) { distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); String selection = selectedApplianceList.getSelectedValue(); Appliance current = installation.findAppliance(selection); ActivityModel activityModel = installation.getPerson().findActivity(selection, true); if (activityModel == null) activityModel = installation.getPerson().findActivity(current); ChartPanel chartPanel = activityModel.createStartTimeBinnedDistributionChart(); distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER); distributionPreviewPanel.validate(); } }); startTimeButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Start Time * button on the Distribution Preview panel of the Train Activity * Models tab. It shows the Start Time Distribution for the selected * object from the list if available. */ @Override public void actionPerformed(ActionEvent arg0) { distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); String selection = selectedApplianceList.getSelectedValue(); Appliance current = installation.findAppliance(selection); ActivityModel activityModel = installation.getPerson().findActivity(selection, true); if (activityModel == null) activityModel = installation.getPerson().findActivity(current); ChartPanel chartPanel = activityModel.createStartTimeDistributionChart(); distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER); distributionPreviewPanel.validate(); } }); durationButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Duration * button on the Distribution Preview panel of the Train Activity * Models tab. It shows the Duration Distribution for the selected * object from the list if available. */ @Override public void actionPerformed(ActionEvent arg0) { distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); String selection = selectedApplianceList.getSelectedValue(); Appliance current = installation.findAppliance(selection); ActivityModel activityModel = installation.getPerson().findActivity(selection, true); if (activityModel == null) activityModel = installation.getPerson().findActivity(current); ChartPanel chartPanel = activityModel.createDurationDistributionChart(); distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER); distributionPreviewPanel.validate(); } }); selectedApplianceList.addListSelectionListener(new ListSelectionListener() { /** * This function is called when the user selects an appliance or activity * from the list of Selected Appliances on the Appliance / Activity * Selection panel of the Train Activity Models tab. Then an example * corresponding consumption model is presented in the Consumption Model * Preview panel. */ @Override public void valueChanged(ListSelectionEvent arg0) { ChartPanel chartPanel = null, chartPanel2 = null, chartPanel3 = null; expectedPowerPanel.removeAll(); expectedPowerPanel.updateUI(); distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); // If there are any appliances / activities on the list if (selectedAppliances.size() >= 1) { // Find the corresponding appliance / activity and show its // consumption model String selection = selectedApplianceList.getSelectedValue(); Appliance currentAppliance = installation.findAppliance(selection); ActivityModel activityModel = installation.getPerson().findActivity(selection, true); // If there is also an Activity model trained, show the corresponding // distribution charts on the Distribution Preview panel if (currentAppliance != null) activityModel = installation.getPerson().findActivity(currentAppliance); if (activityModel == null) activityModel = installation.getPerson().findActivity(selection, true); if (activityModel != null) { dailyTimesButton.setEnabled(true); durationButton.setEnabled(true); startTimeButton.setEnabled(true); startTimeBinnedButton.setEnabled(true); chartPanel2 = activityModel.createDailyTimesDistributionChart(); distributionPreviewPanel.add(chartPanel2, BorderLayout.CENTER); distributionPreviewPanel.validate(); distributionPreviewPanel.updateUI(); chartPanel3 = activityModel.createExpectedPowerChart(); expectedPowerPanel.add(chartPanel3, BorderLayout.CENTER); expectedPowerPanel.validate(); expectedPowerPanel.updateUI(); } else { dailyTimesButton.setEnabled(false); durationButton.setEnabled(false); startTimeButton.setEnabled(false); startTimeBinnedButton.setEnabled(false); } } } }); // RESPONSE TAB // createResponseTab.addComponentListener(new ComponentAdapter() { @Override public void componentHidden(ComponentEvent arg0) { activitySelectList.setSelectedIndex(0); } @Override public void componentShown(ComponentEvent arg0) { activitySelectList.setSelectedIndex(0); } }); previewResponseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Preview Response * button on the Response Parameters panel of the Create Response Models * tab. This button is enabled after selecting activity model, response * type and pricing for testing and presents a preview of the response * model that may be extracted. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); responsePanel.removeAll(); // Find the selected activity ActivityModel activity = installation.getPerson() .findActivity(activitySelectList.getSelectedValue(), false); int response = -1; // Check for the selected response type if (optimalCaseRadioButton.isSelected()) response = 0; else if (normalCaseRadioButton.isSelected()) response = 1; else response = 2; // Parse the pricing schemes double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText()); double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText()); float awareness = (float) (awarenessSlider.getValue()) / 100; float sensitivity = (float) (sensitivitySlider.getValue()) / 100; System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity); // Create a preview chart of the response model ChartPanel chartPanel = installation.getPerson().previewResponse(activity, response, basicScheme, newScheme, awareness, sensitivity); responsePanel.add(chartPanel, BorderLayout.CENTER); responsePanel.validate(); createResponseButton.setEnabled(true); createResponseAllButton.setEnabled(true); dailyResponseButton.setEnabled(true); startResponseButton.setEnabled(true); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); createResponseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Create Response Model * button on the Response Parameters panel of the Create Response Models * tab. This button is enabled after preview results of the selected * activity model, response type and pricing for testing and creates the * response model for the user. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); int responseType = -1; String responseString = ""; // Check for the selected response type if (optimalCaseRadioButton.isSelected()) { responseType = 0; responseString = "Optimal"; } else if (normalCaseRadioButton.isSelected()) { responseType = 1; responseString = "Normal"; } else if (discreteCaseRadioButton.isSelected()) { responseType = 2; responseString = "Discrete"; } // Parse the pricing schemes double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText()); double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText()); // Create the response model ActivityModel activity = installation.getPerson() .findActivity(activitySelectList.getSelectedValue(), false); String response = ""; float awareness = (float) (awarenessSlider.getValue()) / 100; float sensitivity = (float) (sensitivitySlider.getValue()) / 100; System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity); try { response = installation.getPerson().createResponse(activity, responseType, basicScheme, newScheme, awareness, sensitivity); } catch (IOException exc) { exc.printStackTrace(); } // Add the response model extracted to the export model list. int size = exportModelList.getModel().getSize(); // System.out.println(size); if (size > 0) { exportModels = (DefaultListModel<String>) exportModelList.getModel(); String response2 = "", response3 = ""; if (responseString.equalsIgnoreCase("Optimal")) { response2 = response.replace(responseString, "Normal"); response3 = response.replace(responseString, "Discrete"); } else if (responseString.equalsIgnoreCase("Normal")) { response2 = response.replace(responseString, "Optimal"); response3 = response.replace(responseString, "Discrete"); } else { response2 = response.replace(responseString, "Optimal"); response3 = response.replace(responseString, "Normal"); } if (exportModels.contains(response2)) exportModels.removeElement(response2); if (exportModels.contains(response3)) exportModels.removeElement(response3); if (exportModels.contains(response) == false) exportModels.addElement(response); } else { exportModels = new DefaultListModel<String>(); exportModels.addElement(response); exportModelList.setEnabled(true); } exportModelList.setModel(exportModels); if (manyFlag == false) { JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The response model " + response + " was created successfully", "Response Model Created", JOptionPane.INFORMATION_MESSAGE); } } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); createResponseAllButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Create Response All * button on the Response Parameters panel of the Create Response Models * tab. This is achieved by iterating the procedure above for all the * available activity models in the list. */ @Override public void actionPerformed(ActionEvent arg0) { manyFlag = true; for (int i = 0; i < activitySelectList.getModel().getSize(); i++) { activitySelectList.setSelectedIndex(i); createResponseButton.doClick(); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The response models were created successfully", "Response Models Created", JOptionPane.INFORMATION_MESSAGE); manyFlag = false; } }); newPricingSchemePane.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent arg0) { commitButton.setEnabled(true); } }); basicPricingSchemePane.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent arg0) { commitButton.setEnabled(true); } }); commitButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Commit button on the * Pricing Scheme panel of the Create Response Models tab. This button is * enabled after adding the two pricing schemes that are prerequisites for * the creation of a response model. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); boolean basicScheme = false; boolean newScheme = false; int parseBasic = 0; int parseNew = 0; pricingPreviewPanel.removeAll(); // Check if both pricing schemes are entered if (basicPricingSchemePane.getText().equalsIgnoreCase("") == false) basicScheme = true; if (newPricingSchemePane.getText().equalsIgnoreCase("") == false) newScheme = true; // Parse the pricing schemes for errors if (basicScheme) parseBasic = Utils.parsePricingScheme(basicPricingSchemePane.getText()); if (newScheme) parseNew = Utils.parsePricingScheme(newPricingSchemePane.getText()); // If errors are found then present the line the error may be at if (parseBasic != -1) { JFrame error = new JFrame(); JOptionPane.showMessageDialog(error, "Basic Pricing Scheme is not defined correctly. Please check your input in line " + parseBasic + " and try again.", "Inane error", JOptionPane.ERROR_MESSAGE); } else if (parseNew != -1) { JFrame error = new JFrame(); JOptionPane.showMessageDialog(error, "New Pricing Scheme is not defined correctly. Please check your input in line " + parseNew + " and try again.", "Inane error", JOptionPane.ERROR_MESSAGE); } // If no errors are found make a preview chart of the two pricing // schemes else { if (basicScheme && newScheme) { ChartPanel chartPanel = ChartUtils.parsePricingScheme(basicPricingSchemePane.getText(), newPricingSchemePane.getText()); pricingPreviewPanel.add(chartPanel, BorderLayout.CENTER); pricingPreviewPanel.validate(); previewResponseButton.setEnabled(true); } else { JFrame error = new JFrame(); JOptionPane.showMessageDialog(error, "You have not defined both pricing schemes.Please check your input and try again.", "Inane error", JOptionPane.ERROR_MESSAGE); previewResponseButton.setEnabled(false); } } responsePanel.removeAll(); responsePanel.validate(); createResponseButton.setEnabled(false); createResponseAllButton.setEnabled(false); dailyResponseButton.setEnabled(false); startResponseButton.setEnabled(false); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); startResponseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the start time button on * the Preview Response panel of the Create Response Models tab. This * button is enabled after the user has pressed the Response Preview * button in order to see the results of his pricing scheme on a activity * model. It shows the changes in the start time distribution. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); responsePanel.removeAll(); // Find the selected activity ActivityModel activity = installation.getPerson() .findActivity(activitySelectList.getSelectedValue(), false); int response = -1; // Check for the selected response type if (optimalCaseRadioButton.isSelected()) response = 0; else if (normalCaseRadioButton.isSelected()) response = 1; else response = 2; // Parse the pricing schemes double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText()); double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText()); float awareness = (float) (awarenessSlider.getValue()) / 100; float sensitivity = (float) (sensitivitySlider.getValue()) / 100; System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity); // Create a preview chart of the response model ChartPanel chartPanel = installation.getPerson().previewResponse(activity, response, basicScheme, newScheme, awareness, sensitivity); responsePanel.add(chartPanel, BorderLayout.CENTER); responsePanel.validate(); createResponseButton.setEnabled(true); createResponseAllButton.setEnabled(true); dailyResponseButton.setEnabled(true); startResponseButton.setEnabled(true); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); dailyResponseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the start time button on * the Preview Response panel of the Create Response Models tab. This * button is enabled after the user has pressed the Response Preview * button in order to see the results of his pricing scheme on a activity * model. It shows the changes in the daily times distribution. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); responsePanel.removeAll(); // Find the selected activity ActivityModel activity = installation.getPerson() .findActivity(activitySelectList.getSelectedValue(), false); // Parse the pricing schemes double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText()); double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText()); float awareness = (float) (awarenessSlider.getValue()) / 100; float sensitivity = (float) (sensitivitySlider.getValue()) / 100; System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity); // Create a preview chart of the response model ChartPanel chartPanel = installation.getPerson().previewDailyResponse(activity, basicScheme, newScheme, awareness, sensitivity); responsePanel.add(chartPanel, BorderLayout.CENTER); responsePanel.validate(); createResponseButton.setEnabled(true); createResponseAllButton.setEnabled(true); dailyResponseButton.setEnabled(true); startResponseButton.setEnabled(true); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); // EXPORT TAB // exportTab.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent arg0) { exportModelList.setSelectedIndex(0); } }); exportModelList.addListSelectionListener(new ListSelectionListener() { /** * This function is called when the user selects an entity from the * list of models on the Model Export Selection panel of the Export Models * tab. Then the corresponding preview of the entity model is presented in * the * Export Model Preview panel. */ @Override public void valueChanged(ListSelectionEvent arg0) { if (tabbedPane.getSelectedIndex() == 3) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); // Checking if the list has any object if (exportModels.size() > 1) { String selection = exportModelList.getSelectedValue(); // Check to see what type of entity is selected (Installation, // Person, Appliance, Activity, Response) Appliance appliance = installation.findAppliance(selection); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); // Create the appropriate chart for the selected entity and show it. ChartPanel chartPanel = null; if (selection.equalsIgnoreCase(installation.getName())) { try { chartPanel = installation.measurementsChart(); exportDailyButton.setEnabled(false); exportDurationButton.setEnabled(false); exportStartButton.setEnabled(false); exportStartBinnedButton.setEnabled(false); if (trained) exportExpectedPowerButton.setEnabled(true); else exportExpectedPowerButton.setEnabled(false); } catch (IOException e1) { e1.printStackTrace(); } } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) { chartPanel = installation.getPerson().statisticGraphs(); exportDailyButton.setEnabled(false); exportDurationButton.setEnabled(false); exportStartButton.setEnabled(false); exportStartBinnedButton.setEnabled(false); exportExpectedPowerButton.setEnabled(false); } else if (appliance != null) { chartPanel = appliance.consumptionGraph(); exportDailyButton.setEnabled(false); exportDurationButton.setEnabled(false); exportStartButton.setEnabled(false); exportStartBinnedButton.setEnabled(false); exportExpectedPowerButton.setEnabled(false); } else if (activity != null) { chartPanel = activity.createDailyTimesDistributionChart(); activity.status(); exportDailyButton.setEnabled(true); exportDurationButton.setEnabled(true); exportStartButton.setEnabled(true); exportStartBinnedButton.setEnabled(true); exportExpectedPowerButton.setEnabled(true); } else if (response != null) { chartPanel = response.createDailyTimesDistributionChart(); exportDailyButton.setEnabled(true); exportDurationButton.setEnabled(true); exportStartButton.setEnabled(true); exportStartBinnedButton.setEnabled(true); exportExpectedPowerButton.setEnabled(true); } exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } } } }); exportDailyButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Daily Times * button on the Entity Preview panel of the Export Models tab. It shows * the Daily Times Distribution for the selected object from the list. */ @Override public void actionPerformed(ActionEvent arg0) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); String selection = exportModelList.getSelectedValue(); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); ChartPanel chartPanel = null; if (activity != null) chartPanel = activity.createDailyTimesDistributionChart(); else chartPanel = response.createDailyTimesDistributionChart(); exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } }); exportStartBinnedButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Start Time Binned * button on the Entity Preview panel of the Export Models tab. It shows * the Start Time Binned Distribution for the selected object from the * list. */ @Override public void actionPerformed(ActionEvent arg0) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); String selection = exportModelList.getSelectedValue(); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); ChartPanel chartPanel = null; if (activity != null) chartPanel = activity.createStartTimeBinnedDistributionChart(); else chartPanel = response.createStartTimeBinnedDistributionChart(); exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } }); exportStartButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Start Time * button on the Entity Preview panel of the Export Models tab. It shows * the Start Time Distribution for the selected object from the list. */ @Override public void actionPerformed(ActionEvent arg0) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); String selection = exportModelList.getSelectedValue(); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); ChartPanel chartPanel = null; if (activity != null) chartPanel = activity.createStartTimeDistributionChart(); else chartPanel = response.createStartTimeDistributionChart(); exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } }); exportDurationButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Duration * button on the Entity Preview panel of the Export Models tab. It shows * the Duration Distribution for the selected object from the list. */ @Override public void actionPerformed(ActionEvent arg0) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); String selection = exportModelList.getSelectedValue(); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); ChartPanel chartPanel = null; if (activity != null) chartPanel = activity.createDurationDistributionChart(); else chartPanel = response.createDurationDistributionChart(); exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } }); exportExpectedPowerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); String selection = exportModelList.getSelectedValue(); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); ChartPanel chartPanel = null; if (selection.equalsIgnoreCase(installation.getName())) chartPanel = installation.createExpectedPowerChart(); else if (activity != null) chartPanel = activity.createExpectedPowerChart(); else chartPanel = response.createExpectedPowerChart(); exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } }); connectButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Connect button on the * Connection Properties panel of the Export Models tab. It helps the user * to connect to his Cassandra Library and export the models he created * there. */ @Override public void actionPerformed(ActionEvent e) { boolean result = false; // Reads the user credentials and the server to connect to. try { APIUtilities.setUrl(urlTextField.getText()); result = APIUtilities.sendUserCredentials(usernameTextField.getText(), passwordField.getPassword()); } catch (Exception e1) { e1.printStackTrace(); } // If the use credentials are correct if (result) { exportButton.setEnabled(true); exportAllBaseButton.setEnabled(true); exportAllResponseButton.setEnabled(true); householdNameTextField.setEnabled(true); } // Else a error message appears. else { JFrame error = new JFrame(); JOptionPane.showMessageDialog(error, "User Credentials are not correct! Please try again.", "Inane error", JOptionPane.ERROR_MESSAGE); passwordField.setText(""); } } }); passwordField.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent e) { String pass = String.valueOf(passwordField.getPassword()); if (pass.equals("")) { connectButton.setEnabled(false); } else connectButton.setEnabled(true); } }); exportButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Export button on the * Connection Properties panel of the Export Models tab. The entity model * selected from the list is then exported to the User Library in * Cassandra Platform. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Parsing the selected entity and find out what type of entity it is. String selection = exportModelList.getSelectedValue(); Appliance appliance = installation.findAppliance(selection); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); // If it is installation if (selection.equalsIgnoreCase(installation.getName())) { String oldName = installation.getName(); installation.setName(householdNameTextField.getText()); try { installation.setInstallationID(APIUtilities .sendEntity(installation.toJSON(APIUtilities.getUserID()).toString(), "/inst")); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } installation.setName(oldName); JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The installation model " + installation.getName() + " was exported successfully", "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE); } // If it is person else if (selection.equalsIgnoreCase(installation.getPerson().getName())) { try { installation.getPerson().setPersonID(APIUtilities.sendEntity( installation.getPerson().toJSON(APIUtilities.getUserID()).toString(), "/pers")); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The person model " + installation.getPerson().getName() + " was exported successfully", "Person Model Exported", JOptionPane.INFORMATION_MESSAGE); } // If it is appliance else if (appliance != null) { try { appliance.setApplianceID(APIUtilities .sendEntity(appliance.toJSON(APIUtilities.getUserID()).toString(), "/app")); APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(), "/consmod"); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The appliance model " + appliance.getName() + " was exported successfully", "Appliance Model Exported", JOptionPane.INFORMATION_MESSAGE); } // If it is activity else if (activity != null) { String[] applianceTemp = new String[activity.getAppliancesOf().length]; String activityTemp = ""; String durationTemp = ""; String dailyTemp = ""; String startTemp = ""; // For each appliance that participates in the activity for (int i = 0; i < activity.getAppliancesOf().length; i++) { Appliance activityAppliance = activity.getAppliancesOf()[i]; try { // In case the appliances contained in the Activity model are // not // in the database, we create the object there before sending // the // activity model if (activityAppliance.getApplianceID().equalsIgnoreCase("")) { activityAppliance.setApplianceID(APIUtilities.sendEntity( activityAppliance.toJSON(APIUtilities.getUserID()).toString(), "/app")); APIUtilities.sendEntity( activityAppliance.powerConsumptionModelToJSON().toString(), "/consmod"); } applianceTemp[i] = activityAppliance.getApplianceID(); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } try { String[] appliancesID = applianceTemp; // Creating the JSON of the activity model activity.setActivityModelID(APIUtilities.sendEntity( activity.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod")); activityTemp = activity.getActivityModelID(); // Creating the JSON of the distributions activity.getDailyTimes().setDistributionID(APIUtilities.sendEntity( activity.getDailyTimes().toJSON(activityTemp).toString(), "/distr")); activity.setDailyID(activity.getDailyTimes().getDistributionID()); dailyTemp = activity.getDailyID(); activity.getDuration().setDistributionID(APIUtilities .sendEntity(activity.getDuration().toJSON(activityTemp).toString(), "/distr")); activity.setDurationID(activity.getDuration().getDistributionID()); durationTemp = activity.getDurationID(); activity.getStartTime().setDistributionID(APIUtilities .sendEntity(activity.getStartTime().toJSON(activityTemp).toString(), "/distr")); activity.setStartID(activity.getStartTime().getDistributionID()); startTemp = activity.getStartID(); // Adding the JSON of the distributions to the activity model APIUtilities.updateEntity( activity.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod", activityTemp); } catch (AuthenticationException | NoSuchAlgorithmException | IOException e1) { e1.printStackTrace(); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The activity model " + activity.getName() + " was exported successfully", "Activity Model Exported", JOptionPane.INFORMATION_MESSAGE); } // If it is response else if (response != null) { String[] applianceTemp = new String[response.getAppliancesOf().length]; String responseTemp = ""; String durationTemp = ""; String dailyTemp = ""; String startTemp = ""; // For each appliance that participates in the activity for (int i = 0; i < response.getAppliancesOf().length; i++) { Appliance responseAppliance = response.getAppliancesOf()[i]; try { // In case the appliances contained in the Activity model are // not // in the database, we create the object there before sending // the // activity model if (responseAppliance.getApplianceID().equalsIgnoreCase("")) { responseAppliance.setApplianceID(APIUtilities.sendEntity( responseAppliance.toJSON(APIUtilities.getUserID()).toString(), "/app")); APIUtilities.sendEntity( responseAppliance.powerConsumptionModelToJSON().toString(), "/consmod"); } applianceTemp[i] = responseAppliance.getApplianceID(); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } try { String[] appliancesID = applianceTemp; // Creating the JSON of the response response.setActivityModelID(APIUtilities.sendEntity( response.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod")); responseTemp = response.getActivityModelID(); // Creating the JSON of the distributions response.getDailyTimes().setDistributionID(APIUtilities.sendEntity( response.getDailyTimes().toJSON(responseTemp).toString(), "/distr")); response.setDailyID(response.getDailyTimes().getDistributionID()); dailyTemp = response.getDailyID(); response.getDuration().setDistributionID(APIUtilities .sendEntity(response.getDuration().toJSON(responseTemp).toString(), "/distr")); response.setDurationID(response.getDuration().getDistributionID()); durationTemp = response.getDurationID(); response.getStartTime().setDistributionID(APIUtilities .sendEntity(response.getStartTime().toJSON(responseTemp).toString(), "/distr")); response.setStartID(response.getStartTime().getDistributionID()); startTemp = response.getStartID(); // Adding the JSON of the distributions to the activity model APIUtilities.updateEntity( response.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod", responseTemp); } catch (AuthenticationException | NoSuchAlgorithmException | IOException e1) { e1.printStackTrace(); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The response model " + response.getName() + " was exported successfully", "Response Model Exported", JOptionPane.INFORMATION_MESSAGE); } } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); exportAllBaseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Export All Base * button on the Connection Properties panel of the Export Models tab. The * export procedure above is iterated through all the entities available * on the list except for the response models. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); for (int i = 0; i < exportModelList.getModel().getSize(); i++) { exportModelList.setSelectedIndex(i); String selection = exportModelList.getSelectedValue(); Appliance appliance = installation.findAppliance(selection); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); if (selection.equalsIgnoreCase(installation.getName())) { String oldName = installation.getName(); try { installation.setName(householdNameTextField.getText() + " Base"); installation.setInstallationID(APIUtilities.sendEntity( installation.toJSON(APIUtilities.getUserID()).toString(), "/inst")); installation.setName(oldName); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) { try { installation.getPerson().setPersonID(APIUtilities.sendEntity(installation .getPerson().toJSON(installation.getInstallationID()).toString(), "/pers")); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (appliance != null) { try { appliance.setApplianceID(APIUtilities.sendEntity( appliance.toJSON(installation.getInstallationID().toString()).toString(), "/app")); APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(), "/consmod"); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (activity != null) { String[] applianceTemp = new String[activity.getAppliancesOf().length]; String personTemp = ""; String activityTemp = ""; String durationTemp = ""; String dailyTemp = ""; String startTemp = ""; // For each appliance that participates in the activity for (int j = 0; j < activity.getAppliancesOf().length; j++) { Appliance activityAppliance = activity.getAppliancesOf()[j]; applianceTemp[j] = activityAppliance.getApplianceID(); } personTemp = installation.getPerson().getPersonID(); try { activity.setActivityID(APIUtilities .sendEntity(activity.activityToJSON(personTemp).toString(), "/act")); String[] appliancesID = applianceTemp; activity.setActivityModelID(APIUtilities .sendEntity(activity.toJSON(appliancesID).toString(), "/actmod")); activityTemp = activity.getActivityModelID(); activity.getDailyTimes().setDistributionID(APIUtilities.sendEntity( activity.getDailyTimes().toJSON(activityTemp).toString(), "/distr")); activity.setDailyID(activity.getDailyTimes().getDistributionID()); dailyTemp = activity.getDailyID(); activity.getDuration().setDistributionID(APIUtilities.sendEntity( activity.getDuration().toJSON(activityTemp).toString(), "/distr")); activity.setDurationID(activity.getDuration().getDistributionID()); durationTemp = activity.getDurationID(); activity.getStartTime().setDistributionID(APIUtilities.sendEntity( activity.getStartTime().toJSON(activityTemp).toString(), "/distr")); activity.setStartID(activity.getStartTime().getDistributionID()); startTemp = activity.getStartID(); APIUtilities.updateEntity(activity.toJSON(appliancesID).toString(), "/actmod", activityTemp); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (response != null) { } } } finally { root.setCursor(Cursor.getDefaultCursor()); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The installation model " + installation.getName() + " for the base pricing scheme and all the entities contained within were exported successfully", "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE); } }); exportAllResponseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Export All Base * button on the Connection Properties panel of the Export Models tab. The * export procedure above is iterated through all the entities available * on the list except for the activity models. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); for (int i = 0; i < exportModelList.getModel().getSize(); i++) { exportModelList.setSelectedIndex(i); String selection = exportModelList.getSelectedValue(); Appliance appliance = installation.findAppliance(selection); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); if (selection.equalsIgnoreCase(installation.getName())) { String oldName = installation.getName(); try { installation.setName(householdNameTextField.getText() + " Response"); installation.setInstallationID(APIUtilities.sendEntity( installation.toJSON(APIUtilities.getUserID()).toString(), "/inst")); installation.setName(oldName); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) { try { installation.getPerson().setPersonID(APIUtilities.sendEntity(installation .getPerson().toJSON(installation.getInstallationID()).toString(), "/pers")); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (appliance != null) { try { appliance.setApplianceID(APIUtilities.sendEntity( appliance.toJSON(installation.getInstallationID().toString()).toString(), "/app")); APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(), "/consmod"); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (activity != null) { } else if (response != null) { String[] applianceTemp = new String[response.getAppliancesOf().length]; String personTemp = ""; String responseTemp = ""; String durationTemp = ""; String dailyTemp = ""; String startTemp = ""; // For each appliance that participates in the activity for (int j = 0; j < response.getAppliancesOf().length; j++) { Appliance responseAppliance = response.getAppliancesOf()[j]; applianceTemp[j] = responseAppliance.getApplianceID(); } personTemp = installation.getPerson().getPersonID(); try { response.setActivityID(APIUtilities .sendEntity(response.activityToJSON(personTemp).toString(), "/act")); String[] appliancesID = applianceTemp; response.setActivityModelID(APIUtilities .sendEntity(response.toJSON(appliancesID).toString(), "/actmod")); responseTemp = response.getActivityModelID(); response.getDailyTimes().setDistributionID(APIUtilities.sendEntity( response.getDailyTimes().toJSON(responseTemp).toString(), "/distr")); response.setDailyID(response.getDailyTimes().getDistributionID()); dailyTemp = response.getDailyID(); response.getDuration().setDistributionID(APIUtilities.sendEntity( response.getDuration().toJSON(responseTemp).toString(), "/distr")); response.setDurationID(response.getDuration().getDistributionID()); durationTemp = response.getDurationID(); response.getStartTime().setDistributionID(APIUtilities.sendEntity( response.getStartTime().toJSON(responseTemp).toString(), "/distr")); response.setStartID(response.getStartTime().getDistributionID()); startTemp = response.getStartID(); APIUtilities.updateEntity(response.toJSON(appliancesID).toString(), "/actmod", responseTemp); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } } } finally { root.setCursor(Cursor.getDefaultCursor()); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The installation model " + installation.getName() + " for the new pricing scheme and all the entities contained within were exported successfully", "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE); } }); }
From source file:org.kepler.gui.KeplerGraphFrame.java
/** * Open a dialog to prompt the user to save a KAR. Return false if the user * clicks "cancel", and otherwise return true. * /* w ww.j a va2 s.c o m*/ * Overrides Top._queryForSave() * * @return _SAVED if the file is saved, _DISCARDED if the modifications are * discarded, _CANCELED if the operation is canceled by the user, * and _FAILED if the user selects save and the save fails. */ @Override protected int _queryForSave() { Object[] options = { "Save", "Discard changes", "Cancel" }; // making more generic since other items to go in the KAR // may be the reason for querying to save // String query = "Save changes to " + StringUtilities.split(_getName()) // + "?"; String query = "Save changes to KAR?"; // Show the MODAL dialog int selected = JOptionPane.showOptionDialog(this, query, "Save Changes?", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (selected == JOptionPane.YES_OPTION) { JButton saveButton = new JButton("Save Kar"); ExportArchiveAction eaa = new ExportArchiveAction(this); eaa.setRefreshFrameAfterSave(false); // if the file already exists, call ExportArchiveAction.setSave() // so that the save as file dialog does is not used. KARFile karFile = KARManager.getInstance().get(this); if (karFile != null) { File file = karFile.getFileLocation(); if (file.canWrite()) { eaa.setSaveFile(file); } } saveButton.addActionListener(eaa); saveButton.doClick(); if (eaa.saveSucceeded()) { setModified(false); return _SAVED; } else { return _FAILED; } } if (selected == JOptionPane.NO_OPTION) { return _DISCARDED; } return _CANCELED; }
From source file:org.metawidget.integrationtest.swing.allwidgets.SwingAllWidgetsTest.java
protected void runTest(AdvancedWidgetProcessor<JComponent, SwingMetawidget> processor) throws Exception { // Model// w w w.j a v a2 s .c o m AllWidgets allWidgets = new AllWidgets$$EnhancerByCGLIB$$1234(); // App SwingMetawidget metawidget = new SwingMetawidget(); metawidget.setConfig("org/metawidget/integrationtest/swing/allwidgets/metawidget.xml"); metawidget.addWidgetProcessor(processor); metawidget.addWidgetProcessor(new ReflectionBindingProcessor()); metawidget.setMetawidgetLayout(new SeparatorLayoutDecorator(new SeparatorLayoutDecoratorConfig().setLayout( new org.metawidget.swing.layout.GridBagLayout(new GridBagLayoutConfig().setNumberOfColumns(2))))); metawidget.setToInspect(allWidgets); metawidget.add(new Stub("mystery")); // Test missing components try { metawidget.getValue("no-such-component"); fail(); } catch (MetawidgetException e1) { assertEquals("No component named 'no-such-component'", e1.getMessage()); try { metawidget.getValue("textbox", "no-such-component"); fail(); } catch (MetawidgetException e2) { assertEquals("No component named 'textbox', 'no-such-component'", e2.getMessage()); try { metawidget.getValue("textbox", "no-such-component1", "no-such-component2"); fail(); } catch (MetawidgetException e3) { assertEquals( "No such component 'no-such-component1' of 'textbox', 'no-such-component1', 'no-such-component2'", e3.getMessage()); } } } try { metawidget.setValue(null, "no-such-component"); fail(); } catch (MetawidgetException e1) { assertEquals("No component named 'no-such-component'", e1.getMessage()); try { metawidget.setValue(null, "textbox", "no-such-component"); fail(); } catch (MetawidgetException e2) { assertEquals("No component named 'textbox', 'no-such-component'", e2.getMessage()); try { metawidget.setValue(null, "textbox", "no-such-component1", "no-such-component2"); fail(); } catch (MetawidgetException e3) { assertEquals( "No such component 'no-such-component1' of 'textbox', 'no-such-component1', 'no-such-component2'", e3.getMessage()); } } } // Check what created, and edit it assertEquals("Textbox*:", ((JLabel) metawidget.getComponent(0)).getText()); assertTrue(metawidget.getComponent(1) instanceof JTextField); assertEquals("Textbox", metawidget.getValue("textbox")); ((JTextField) metawidget.getComponent(1)).setText("Textbox1"); assertEquals("Limited Textbox:", ((JLabel) metawidget.getComponent(2)).getText()); assertTrue(metawidget.getComponent(3) instanceof JTextField); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(3)).gridx); assertEquals("Limited Textbox", metawidget.getValue("limitedTextbox")); ((JTextField) metawidget.getComponent(3)).setText("Limited Textbox1"); assertEquals("Textarea:", ((JLabel) metawidget.getComponent(4)).getText()); assertTrue(metawidget.getComponent(5) instanceof JScrollPane); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(5)).gridx); assertEquals("Textarea", metawidget.getValue("textarea")); JTextArea textarea = (JTextArea) ((JScrollPane) metawidget.getComponent(5)).getViewport().getView(); assertEquals(2, textarea.getRows()); assertEquals(true, textarea.getLineWrap()); assertEquals(true, textarea.getWrapStyleWord()); textarea.setText("Textarea1"); assertEquals("Password:", ((JLabel) metawidget.getComponent(6)).getText()); assertTrue(metawidget.getComponent(7) instanceof JPasswordField); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(7)).gridx); assertEquals("Password", metawidget.getValue("password")); ((JPasswordField) metawidget.getComponent(7)).setText("Password1"); // Primitives assertEquals("Byte Primitive:", ((JLabel) metawidget.getComponent(8)).getText()); assertTrue(metawidget.getComponent(9) instanceof JSpinner); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(9)).gridx); assertTrue(Byte.MAX_VALUE == (Byte) metawidget.getValue("bytePrimitive")); assertTrue(-5 == (Byte) ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(9)).getModel()) .getMinimum()); assertTrue( Byte.MAX_VALUE == (Byte) ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(9)).getModel()) .getMaximum()); assertEquals(0, ((JSpinner.DefaultEditor) ((JSpinner) metawidget.getComponent(9)).getEditor()) .getTextField().getColumns()); JSpinner spinner = (JSpinner) metawidget.getComponent(9); spinner.setValue(spinner.getModel().getPreviousValue()); assertEquals("Byte Object:", ((JLabel) metawidget.getComponent(10)).getText()); assertTrue(metawidget.getComponent(11) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(11)).gridx); assertEquals(String.valueOf(Byte.MIN_VALUE), metawidget.getValue("byteObject")); ((JTextField) metawidget.getComponent(11)).setText(String.valueOf(Byte.MIN_VALUE + 1)); assertEquals("Short Primitive:", ((JLabel) metawidget.getComponent(12)).getText()); assertTrue(metawidget.getComponent(13) instanceof JSpinner); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(13)).gridx); assertTrue(Short.MAX_VALUE == (Short) metawidget.getValue("shortPrimitive")); assertTrue(-6 == (Short) ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(13)).getModel()) .getMinimum()); assertTrue(Short.MAX_VALUE == (Short) ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(13)) .getModel()).getMaximum()); spinner = (JSpinner) metawidget.getComponent(13); assertEquals(0, ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().getColumns()); spinner.setValue(spinner.getModel().getPreviousValue()); assertEquals("Short Object:", ((JLabel) metawidget.getComponent(14)).getText()); assertTrue(metawidget.getComponent(15) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(15)).gridx); assertEquals(String.valueOf(Short.MIN_VALUE), metawidget.getValue("shortObject")); ((JTextField) metawidget.getComponent(15)).setText(String.valueOf(Short.MIN_VALUE + 1)); assertEquals("Int Primitive:", ((JLabel) metawidget.getComponent(16)).getText()); assertTrue(metawidget.getComponent(17) instanceof JSpinner); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(17)).gridx); assertTrue(Integer.MAX_VALUE == (Integer) metawidget.getValue("intPrimitive")); assertTrue(Integer.MIN_VALUE == (Integer) ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(17)) .getModel()).getMinimum()); assertTrue(Integer.MAX_VALUE == (Integer) ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(17)) .getModel()).getMaximum()); spinner = (JSpinner) metawidget.getComponent(17); assertEquals(0, ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().getColumns()); spinner.setValue(spinner.getModel().getPreviousValue()); assertEquals("Integer Object:", ((JLabel) metawidget.getComponent(18)).getText()); assertTrue(metawidget.getComponent(19) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(19)).gridx); assertEquals(String.valueOf(Integer.MIN_VALUE), metawidget.getValue("integerObject")); ((JTextField) metawidget.getComponent(19)).setText(String.valueOf(Integer.MIN_VALUE + 1)); assertEquals("Ranged Int:", ((JLabel) metawidget.getComponent(20)).getText()); assertTrue(metawidget.getComponent(21) instanceof JSlider); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(21)).gridx); assertEquals(1, ((JSlider) metawidget.getComponent(21)).getMinimum()); assertEquals(100, ((JSlider) metawidget.getComponent(21)).getMaximum()); assertTrue(32 == (Integer) metawidget.getValue("rangedInt")); ((JSlider) metawidget.getComponent(21)).setValue(33); assertEquals("Ranged Integer:", ((JLabel) metawidget.getComponent(22)).getText()); assertTrue(metawidget.getComponent(23) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(23)).gridx); assertEquals("33", metawidget.getValue("rangedInteger")); ((JTextField) metawidget.getComponent(23)).setText(String.valueOf(34)); assertEquals("Long Primitive:", ((JLabel) metawidget.getComponent(24)).getText()); assertTrue(metawidget.getComponent(25) instanceof JSpinner); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(25)).gridx); assertTrue(42 == (Long) metawidget.getValue("longPrimitive")); assertTrue(-7 == (Long) ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(25)).getModel()) .getMinimum()); assertTrue( Long.MAX_VALUE == (Long) ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(25)).getModel()) .getMaximum()); spinner = (JSpinner) metawidget.getComponent(25); assertEquals(0, ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().getColumns()); spinner.setValue(spinner.getModel().getNextValue()); assertTrue(metawidget.getComponent(26) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(26)).gridx); assertEquals("43", metawidget.getValue("longObject")); ((JTextField) metawidget.getComponent(26)).setText("44"); assertEquals("Float Primitive:", ((JLabel) metawidget.getComponent(27)).getText()); assertTrue(metawidget.getComponent(28) instanceof JSpinner); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(28)).gridx); assertEquals(4.2f, metawidget.getValue("floatPrimitive")); assertEquals(-Float.MAX_VALUE, ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(28)).getModel()).getMinimum()); assertTrue(2048 == (Float) ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(28)).getModel()) .getMaximum()); spinner = (JSpinner) metawidget.getComponent(28); assertEquals(0, ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().getColumns()); spinner.setValue(spinner.getModel().getNextValue()); assertEquals("nullInBundle:", ((JLabel) metawidget.getComponent(29)).getText()); assertTrue(metawidget.getComponent(30) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(30)).gridx); assertEquals("4.3", metawidget.getValue("floatObject")); ((JTextField) metawidget.getComponent(30)).setText("5.4"); assertEquals("Double Primitive:", ((JLabel) metawidget.getComponent(31)).getText()); assertTrue(metawidget.getComponent(32) instanceof JSpinner); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(32)).gridx); assertEquals(42.2d, metawidget.getValue("doublePrimitive")); assertTrue(-8 == (Double) ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(32)).getModel()) .getMinimum()); assertEquals(Double.MAX_VALUE, ((SpinnerNumberModel) ((JSpinner) metawidget.getComponent(32)).getModel()).getMaximum()); spinner = (JSpinner) metawidget.getComponent(32); assertEquals(0, ((JSpinner.DefaultEditor) spinner.getEditor()).getTextField().getColumns()); spinner.setValue(spinner.getModel().getNextValue()); assertTrue(metawidget.getComponent(33) instanceof JTextField); assertEquals(0, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(33)).gridx); assertEquals(2, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(33)).gridwidth); assertEquals("43.3", metawidget.getValue("doubleObject")); ((JTextField) metawidget.getComponent(33)).setText("54.4"); assertEquals("Char Primitive:", ((JLabel) metawidget.getComponent(34)).getText()); assertTrue(metawidget.getComponent(35) instanceof JTextField); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(35)).gridx); assertEquals("A", metawidget.getValue("charPrimitive")); ((JTextField) metawidget.getComponent(35)).setText("Z"); assertEquals("Character Object:", ((JLabel) metawidget.getComponent(36)).getText()); assertTrue(metawidget.getComponent(37) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(37)).gridx); assertEquals("Z", metawidget.getValue("characterObject")); ((JTextField) metawidget.getComponent(37)).setText("A"); assertEquals("Boolean Primitive:", ((JLabel) metawidget.getComponent(38)).getText()); assertTrue(metawidget.getComponent(39) instanceof JCheckBox); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(39)).gridx); assertTrue(false == (Boolean) metawidget.getValue("booleanPrimitive")); ((JCheckBox) metawidget.getComponent(39)).setSelected(true); assertEquals("Boolean Object:", ((JLabel) metawidget.getComponent(40)).getText()); assertTrue(metawidget.getComponent(41) instanceof JComboBox); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(37)).gridx); assertEquals(3, ((JComboBox) metawidget.getComponent(41)).getItemCount()); assertEquals(Boolean.TRUE, metawidget.getValue("booleanObject")); ((JComboBox) metawidget.getComponent(41)).setSelectedItem(Boolean.FALSE); assertEquals("Dropdown:", ((JLabel) metawidget.getComponent(42)).getText()); assertTrue(metawidget.getComponent(43) instanceof JComboBox); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(43)).gridx); assertEquals(4, ((JComboBox) metawidget.getComponent(43)).getItemCount()); assertEquals("dropdown1", metawidget.getValue("dropdown")); ((JComboBox) metawidget.getComponent(43)).setSelectedItem("foo1"); assertEquals("Dropdown With Labels:", ((JLabel) metawidget.getComponent(44)).getText()); assertTrue(metawidget.getComponent(45) instanceof JComboBox); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(45)).gridx); JComboBox combo = (JComboBox) metawidget.getComponent(45); assertEquals(5, combo.getItemCount()); assertEquals("Foo #2", ((JLabel) combo.getRenderer().getListCellRendererComponent(new JList(), "foo2", 1, false, false)) .getText()); assertEquals("Dropdown #2", ((JLabel) combo.getRenderer().getListCellRendererComponent(new JList(), "dropdown2", 1, false, false)).getText()); assertEquals("Bar #2", ((JLabel) combo.getRenderer().getListCellRendererComponent(new JList(), "bar2", 1, false, false)) .getText()); assertEquals("Baz #2", ((JLabel) combo.getRenderer().getListCellRendererComponent(new JList(), "baz2", 1, false, false)) .getText()); assertEquals("dropdown2", metawidget.getValue("dropdownWithLabels")); ((JComboBox) metawidget.getComponent(45)).setSelectedItem("bar2"); assertEquals("Not Null Dropdown:", ((JLabel) metawidget.getComponent(46)).getText()); assertTrue(metawidget.getComponent(47) instanceof JComboBox); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(47)).gridx); assertEquals(3, ((JComboBox) metawidget.getComponent(47)).getItemCount()); assertTrue(0 == (Byte) metawidget.getValue("notNullDropdown")); ((JComboBox) metawidget.getComponent(47)).setSelectedItem((byte) 1); assertEquals("Not Null Object Dropdown*:", ((JLabel) metawidget.getComponent(48)).getText()); assertTrue(metawidget.getComponent(49) instanceof JComboBox); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(49)).gridx); assertEquals(6, ((JComboBox) metawidget.getComponent(49)).getItemCount()); assertEquals("dropdown3", metawidget.getValue("notNullObjectDropdown")); ((JComboBox) metawidget.getComponent(49)).setSelectedIndex(0); assertEquals("Nested Widgets:", ((JLabel) metawidget.getComponent(50)).getText()); assertTrue(metawidget.getComponent(51) instanceof SwingMetawidget); SwingMetawidget metawidgetNested = (SwingMetawidget) metawidget.getComponent(51); assertEquals("Further Nested Widgets:", ((JLabel) metawidgetNested.getComponent(0)).getText()); assertEquals(1, ((GridBagLayout) metawidgetNested.getLayout()) .getConstraints(metawidgetNested.getComponent(1)).gridx); SwingMetawidget metawidgetFurtherNested = (SwingMetawidget) metawidgetNested.getComponent(1); assertEquals("Further Nested Widgets:", ((JLabel) metawidgetFurtherNested.getComponent(0)).getText()); assertTrue(metawidgetFurtherNested.getComponent(1) instanceof SwingMetawidget); assertEquals(((SwingMetawidget) metawidgetFurtherNested.getComponent(1)).getComponentCount(), 0); assertEquals("Nested Textbox 1:", ((JLabel) metawidgetFurtherNested.getComponent(2)).getText()); assertTrue(metawidgetFurtherNested.getComponent(3) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidgetFurtherNested.getLayout()) .getConstraints(metawidgetFurtherNested.getComponent(3)).gridx); assertEquals("Nested Textbox 1", metawidget.getValue("nestedWidgets", "furtherNestedWidgets", "nestedTextbox1")); ((JTextField) metawidgetFurtherNested.getComponent(3)).setText("Nested Textbox 1.1 (further)"); assertEquals("Nested Textbox 2:", ((JLabel) metawidgetFurtherNested.getComponent(4)).getText()); assertTrue(metawidgetFurtherNested.getComponent(5) instanceof JTextField); // (should be 1, as in next row, if getEffectiveNumberOfColumns is working) assertEquals(1, ((GridBagLayout) metawidgetFurtherNested.getLayout()) .getConstraints(metawidgetFurtherNested.getComponent(5)).gridx); assertEquals("Nested Textbox 2", metawidget.getValue("nestedWidgets", "furtherNestedWidgets", "nestedTextbox2")); ((JTextField) metawidgetFurtherNested.getComponent(5)).setText("Nested Textbox 2.2 (further)"); assertEquals("Nested Textbox 1:", ((JLabel) metawidgetNested.getComponent(2)).getText()); assertTrue(metawidgetNested.getComponent(3) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidgetNested.getLayout()) .getConstraints(metawidgetNested.getComponent(3)).gridx); assertEquals("Nested Textbox 1", metawidget.getValue("nestedWidgets", "nestedTextbox1")); ((JTextField) metawidgetNested.getComponent(3)).setText("Nested Textbox 1.1"); assertEquals("Nested Textbox 2:", ((JLabel) metawidgetNested.getComponent(4)).getText()); assertTrue(metawidgetNested.getComponent(5) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidgetNested.getLayout()) .getConstraints(metawidgetNested.getComponent(5)).gridx); assertEquals("Nested Textbox 2", metawidget.getValue("nestedWidgets", "nestedTextbox2")); ((JTextField) metawidgetNested.getComponent(5)).setText("Nested Textbox 2.2"); assertEquals("Read Only Nested Widgets:", ((JLabel) metawidget.getComponent(52)).getText()); assertTrue(metawidget.getComponent(53) instanceof SwingMetawidget); metawidgetNested = (SwingMetawidget) metawidget.getComponent(53); assertEquals("Nested Textbox 1:", ((JLabel) metawidgetNested.getComponent(2)).getText()); assertTrue(metawidgetNested.getComponent(3) instanceof JLabel); assertEquals(1, ((GridBagLayout) metawidgetNested.getLayout()) .getConstraints(metawidgetNested.getComponent(3)).gridx); assertEquals("Nested Textbox 1", metawidget.getValue("readOnlyNestedWidgets", "nestedTextbox1")); assertEquals("Nested Textbox 2:", ((JLabel) metawidgetNested.getComponent(4)).getText()); assertTrue(metawidgetNested.getComponent(5) instanceof JLabel); assertEquals(1, ((GridBagLayout) metawidgetNested.getLayout()) .getConstraints(metawidgetNested.getComponent(5)).gridx); assertEquals("Nested Textbox 2", metawidget.getValue("readOnlyNestedWidgets", "nestedTextbox2")); assertEquals("Nested Widgets Dont Expand:", ((JLabel) metawidget.getComponent(54)).getText()); assertEquals("Nested Textbox 1, Nested Textbox 2", ((JTextField) metawidget.getComponent(55)).getText()); ((JTextField) metawidget.getComponent(55)).setText("Nested Textbox 1.01, Nested Textbox 2.02"); assertEquals("Read Only Nested Widgets Dont Expand:", ((JLabel) metawidget.getComponent(56)).getText()); assertEquals("Nested Textbox 1, Nested Textbox 2", ((JLabel) metawidget.getComponent(57)).getText()); assertEquals("Date:", ((JLabel) metawidget.getComponent(58)).getText()); assertTrue(metawidget.getComponent(59) instanceof JTextField); assertEquals(1, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(59)).gridx); DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT); assertEquals(dateFormat.format(allWidgets.getDate()), metawidget.getValue("date")); ((JTextField) metawidget.getComponent(59)).setText("bad date"); JPanel separatorPanel = (JPanel) metawidget.getComponent(60); assertEquals("Section Break", ((JLabel) separatorPanel.getComponent(0)).getText()); assertEquals(GridBagConstraints.REMAINDER, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(60)).gridwidth); assertTrue(separatorPanel.getComponent(1) instanceof JSeparator); assertEquals("Read Only:", ((JLabel) metawidget.getComponent(61)).getText()); assertTrue(metawidget.getComponent(62) instanceof JLabel); assertEquals("Read Only", metawidget.getValue("readOnly")); assertTrue(metawidget.getComponent(63) instanceof JButton); assertEquals(3, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(63)).gridx); assertEquals(GridBagConstraints.NONE, ((GridBagLayout) metawidget.getLayout()).getConstraints(metawidget.getComponent(63)).fill); JButton button = ((JButton) metawidget.getComponent(63)); assertEquals("Do Action", button.getText()); assertTrue(button.isEnabled()); try { button.doClick(); fail(); } catch (Exception e) { assertEquals("doAction called", e.getCause().getCause().getMessage()); } assertEquals(64, metawidget.getComponentCount()); // Check painting JFrame frame = new JFrame(); metawidget.paint(frame.getGraphics()); // Check MetawidgetException try { processor.getClass().getMethod("save", SwingMetawidget.class).invoke(processor, metawidget); fail(); } catch (Exception e) { assertEquals("Could not parse 'bad date'", e.getCause().getCause().getMessage()); } // Check saving String now = dateFormat.format(new GregorianCalendar().getTime()); ((JTextField) metawidget.getComponent(59)).setText(now); processor.getClass().getMethod("save", SwingMetawidget.class).invoke(processor, metawidget); // Check read-only metawidget.setReadOnly(true); assertEquals("Textbox:", ((JLabel) metawidget.getComponent(0)).getText()); assertEquals("Textbox1", ((JLabel) metawidget.getComponent(1)).getText()); assertEquals("Limited Textbox:", ((JLabel) metawidget.getComponent(2)).getText()); assertEquals("Limited Textbox1", ((JLabel) metawidget.getComponent(3)).getText()); assertEquals("Textarea:", ((JLabel) metawidget.getComponent(4)).getText()); assertEquals("Textarea1", ((JTextArea) ((JScrollPane) metawidget.getComponent(5)).getViewport().getView()).getText()); assertEquals("Password:", ((JLabel) metawidget.getComponent(6)).getText()); assertTrue(metawidget.getComponent(7) instanceof JPanel); assertEquals("Byte Primitive:", ((JLabel) metawidget.getComponent(8)).getText()); assertEquals("126", ((JLabel) metawidget.getComponent(9)).getText()); assertEquals("Byte Object:", ((JLabel) metawidget.getComponent(10)).getText()); assertEquals("-127", ((JLabel) metawidget.getComponent(11)).getText()); assertEquals("Short Primitive:", ((JLabel) metawidget.getComponent(12)).getText()); assertEquals("32766", ((JLabel) metawidget.getComponent(13)).getText()); assertEquals("Short Object:", ((JLabel) metawidget.getComponent(14)).getText()); assertEquals("-32767", ((JLabel) metawidget.getComponent(15)).getText()); assertEquals("Int Primitive:", ((JLabel) metawidget.getComponent(16)).getText()); assertEquals("2147483646", ((JLabel) metawidget.getComponent(17)).getText()); assertEquals("Integer Object:", ((JLabel) metawidget.getComponent(18)).getText()); assertEquals("-2147483647", ((JLabel) metawidget.getComponent(19)).getText()); assertEquals("Ranged Int:", ((JLabel) metawidget.getComponent(20)).getText()); assertEquals("33", ((JLabel) metawidget.getComponent(21)).getText()); assertEquals("Ranged Integer:", ((JLabel) metawidget.getComponent(22)).getText()); assertEquals("34", ((JLabel) metawidget.getComponent(23)).getText()); assertEquals("Long Primitive:", ((JLabel) metawidget.getComponent(24)).getText()); assertEquals("43", ((JLabel) metawidget.getComponent(25)).getText()); assertEquals("44", ((JLabel) metawidget.getComponent(26)).getText()); assertEquals("Float Primitive:", ((JLabel) metawidget.getComponent(27)).getText()); assertTrue(((JLabel) metawidget.getComponent(28)).getText().startsWith("4.3") || ((JLabel) metawidget.getComponent(28)).getText().startsWith("4.299")); assertEquals("nullInBundle:", ((JLabel) metawidget.getComponent(29)).getText()); assertEquals("5.4", ((JLabel) metawidget.getComponent(30)).getText()); assertEquals("Double Primitive:", ((JLabel) metawidget.getComponent(31)).getText()); assertTrue(((JLabel) metawidget.getComponent(32)).getText().startsWith("42.3") || ((JLabel) metawidget.getComponent(32)).getText().startsWith("42.299")); assertEquals("54.4", ((JLabel) metawidget.getComponent(33)).getText()); assertEquals("Char Primitive:", ((JLabel) metawidget.getComponent(34)).getText()); assertEquals("Z", ((JLabel) metawidget.getComponent(35)).getText()); assertEquals("Character Object:", ((JLabel) metawidget.getComponent(36)).getText()); assertEquals("A", ((JLabel) metawidget.getComponent(37)).getText()); assertEquals("Boolean Primitive:", ((JLabel) metawidget.getComponent(38)).getText()); assertEquals("true", ((JLabel) metawidget.getComponent(39)).getText()); assertEquals("Boolean Object:", ((JLabel) metawidget.getComponent(40)).getText()); assertEquals("No", ((JLabel) metawidget.getComponent(41)).getText()); assertEquals("Dropdown:", ((JLabel) metawidget.getComponent(42)).getText()); assertEquals("foo1", ((JLabel) metawidget.getComponent(43)).getText()); assertEquals("Dropdown With Labels:", ((JLabel) metawidget.getComponent(44)).getText()); assertEquals("Bar #2", ((JLabel) metawidget.getComponent(45)).getText()); assertEquals("Not Null Dropdown:", ((JLabel) metawidget.getComponent(46)).getText()); assertEquals("1", ((JLabel) metawidget.getComponent(47)).getText()); assertEquals("Not Null Object Dropdown:", ((JLabel) metawidget.getComponent(48)).getText()); assertEquals("foo3", ((JLabel) metawidget.getComponent(49)).getText()); assertEquals("Nested Widgets:", ((JLabel) metawidget.getComponent(50)).getText()); assertEquals("Further Nested Widgets:", ((JLabel) ((SwingMetawidget) metawidget.getComponent(51)).getComponent(0)).getText()); assertEquals("Further Nested Widgets:", ((JLabel) ((SwingMetawidget) ((SwingMetawidget) metawidget.getComponent(51)).getComponent(1)) .getComponent(0)).getText()); assertEquals("Nested Textbox 1:", ((JLabel) ((SwingMetawidget) ((SwingMetawidget) metawidget.getComponent(51)).getComponent(1)) .getComponent(2)).getText()); assertEquals("Nested Textbox 1.1 (further)", ((JLabel) ((SwingMetawidget) ((SwingMetawidget) metawidget.getComponent(51)).getComponent(1)) .getComponent(3)).getText()); assertEquals("Nested Textbox 2:", ((JLabel) ((SwingMetawidget) ((SwingMetawidget) metawidget.getComponent(51)).getComponent(1)) .getComponent(4)).getText()); assertEquals("Nested Textbox 2.2 (further)", ((JLabel) ((SwingMetawidget) ((SwingMetawidget) metawidget.getComponent(51)).getComponent(1)) .getComponent(5)).getText()); assertEquals("Nested Textbox 1:", ((JLabel) ((SwingMetawidget) metawidget.getComponent(51)).getComponent(2)).getText()); assertEquals("Nested Textbox 1.1", ((JLabel) ((SwingMetawidget) metawidget.getComponent(51)).getComponent(3)).getText()); assertEquals("Nested Textbox 2:", ((JLabel) ((SwingMetawidget) metawidget.getComponent(51)).getComponent(4)).getText()); assertEquals("Nested Textbox 2.2", ((JLabel) ((SwingMetawidget) metawidget.getComponent(51)).getComponent(5)).getText()); assertEquals("Read Only Nested Widgets:", ((JLabel) metawidget.getComponent(52)).getText()); assertEquals("Further Nested Widgets:", ((JLabel) ((SwingMetawidget) metawidget.getComponent(53)).getComponent(0)).getText()); assertEquals("Nested Textbox 1:", ((JLabel) ((SwingMetawidget) metawidget.getComponent(53)).getComponent(2)).getText()); assertEquals("Nested Textbox 1", ((JLabel) ((SwingMetawidget) metawidget.getComponent(53)).getComponent(3)).getText()); assertEquals("Nested Textbox 2:", ((JLabel) ((SwingMetawidget) metawidget.getComponent(53)).getComponent(4)).getText()); assertEquals("Nested Textbox 2", ((JLabel) ((SwingMetawidget) metawidget.getComponent(53)).getComponent(5)).getText()); assertEquals("Nested Widgets Dont Expand:", ((JLabel) metawidget.getComponent(54)).getText()); assertEquals("Nested Textbox 1.01, Nested Textbox 2.02", ((JLabel) metawidget.getComponent(55)).getText()); assertEquals("Read Only Nested Widgets Dont Expand:", ((JLabel) metawidget.getComponent(56)).getText()); assertEquals("Nested Textbox 1, Nested Textbox 2", ((JLabel) metawidget.getComponent(57)).getText()); assertEquals("Date:", ((JLabel) metawidget.getComponent(58)).getText()); assertEquals(now, ((JLabel) metawidget.getComponent(59)).getText()); assertEquals("Section Break", ((JLabel) ((JPanel) metawidget.getComponent(60)).getComponent(0)).getText()); assertEquals("Read Only:", ((JLabel) metawidget.getComponent(61)).getText()); assertEquals("Read Only", ((JLabel) metawidget.getComponent(62)).getText()); assertEquals("Do Action", ((JButton) metawidget.getComponent(63)).getText()); assertTrue(!((JButton) metawidget.getComponent(63)).isEnabled()); assertEquals(metawidget.getComponentCount(), 64); // Test Binding.onStartBuild clears the state assertTrue(null != metawidget.getClientProperty(processor.getClass())); processor.onStartBuild(metawidget); assertEquals(null, metawidget.getClientProperty(processor.getClass())); }
From source file:org.ut.biolab.medsavant.client.util.ClientMiscUtils.java
/** * Register the escape key so that it can be used to cancel the associated JDialog. *//*from ww w . j a v a 2s . c o m*/ public static void registerCancelButton(final JButton cancelButton) { KeyStroke stroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); JDialog dialog = (JDialog) SwingUtilities.getWindowAncestor(cancelButton); dialog.getRootPane().registerKeyboardAction(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { cancelButton.doClick(); } }, stroke, JComponent.WHEN_IN_FOCUSED_WINDOW); }