List of usage examples for javax.swing JFrame setBounds
public void setBounds(int x, int y, int width, int height)
The width or height values are automatically enlarged if either is less than the minimum size as specified by previous call to setMinimumSize .
From source file:edu.ku.brc.ui.UIHelper.java
/** * @param frame to be positioned//from w ww . j ava2 s . c om * * positions frame on screen relative to position of TOPFRAME. * Sets frame.alwaysOnTop to true if TOPFRAME is maximized. */ public static void positionFrameRelativeToTopFrame(final JFrame frame) { // not sure of safest surest way to get main window??? JFrame topFrame = (JFrame) UIRegistry.getTopWindow(); // for now this just sets the top of frame to the top of topFrame // if there is room on the left side of topFrame, frame is set so it's right edge is next to topFrame's left edge. // otherwise, if frame will fit, frame's left edge is aligned with topFrame's right edge. // If it won't fit then frame's right edge is aligned with right of edge of screen. if (topFrame != null) { int x = 0; int y = topFrame.getY(); Rectangle screenRect = topFrame.getGraphicsConfiguration().getBounds(); if (topFrame.getX() >= frame.getWidth()) { x = topFrame.getX() - frame.getWidth(); } else if (screenRect.width - topFrame.getX() - topFrame.getWidth() >= frame.getWidth()) { x = topFrame.getWidth(); } else { x = screenRect.width - frame.getWidth(); } frame.setBounds(x, y, frame.getWidth(), frame.getHeight()); frame.setAlwaysOnTop(topFrame.getExtendedState() == Frame.MAXIMIZED_BOTH || topFrame.getExtendedState() == Frame.MAXIMIZED_VERT || topFrame.getExtendedState() == Frame.MAXIMIZED_HORIZ); } }
From source file:com.maxl.java.amikodesk.AMiKoDesk.java
private static void createAndShowFullGUI() { // Create and setup window final JFrame jframe = new JFrame(Constants.APP_NAME); jframe.setName(Constants.APP_NAME + ".main"); int min_width = CML_OPT_WIDTH; int min_height = CML_OPT_HEIGHT; jframe.setPreferredSize(new Dimension(min_width, min_height)); jframe.setMinimumSize(new Dimension(min_width, min_height)); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); int x = (screen.width - min_width) / 2; int y = (screen.height - min_height) / 2; jframe.setBounds(x, y, min_width, min_height); // Set application icon if (Utilities.appCustomization().equals("ywesee")) { ImageIcon img = new ImageIcon(Constants.AMIKO_ICON); jframe.setIconImage(img.getImage()); } else if (Utilities.appCustomization().equals("desitin")) { ImageIcon img = new ImageIcon(Constants.DESITIN_ICON); jframe.setIconImage(img.getImage()); } else if (Utilities.appCustomization().equals("meddrugs")) { ImageIcon img = new ImageIcon(Constants.MEDDRUGS_ICON); jframe.setIconImage(img.getImage()); } else if (Utilities.appCustomization().equals("zurrose")) { ImageIcon img = new ImageIcon(Constants.AMIKO_ICON); jframe.setIconImage(img.getImage()); }//from www . j a v a2 s. c o m // ------ Setup menubar ------ JMenuBar menu_bar = new JMenuBar(); // menu_bar.add(Box.createHorizontalGlue()); // --> aligns menu items to the right! // -- Menu "Datei" -- JMenu datei_menu = new JMenu("Datei"); if (Utilities.appLanguage().equals("fr")) datei_menu.setText("Fichier"); menu_bar.add(datei_menu); JMenuItem print_item = new JMenuItem("Drucken..."); JMenuItem settings_item = new JMenuItem(m_rb.getString("settings") + "..."); JMenuItem quit_item = new JMenuItem("Beenden"); if (Utilities.appLanguage().equals("fr")) { print_item.setText("Imprimer"); quit_item.setText("Terminer"); } datei_menu.add(print_item); datei_menu.addSeparator(); datei_menu.add(settings_item); datei_menu.addSeparator(); datei_menu.add(quit_item); // -- Menu "Aktualisieren" -- JMenu update_menu = new JMenu("Aktualisieren"); if (Utilities.appLanguage().equals("fr")) update_menu.setText("Mise jour"); menu_bar.add(update_menu); final JMenuItem updatedb_item = new JMenuItem("Aktualisieren via Internet..."); updatedb_item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, ActionEvent.CTRL_MASK)); JMenuItem choosedb_item = new JMenuItem("Aktualisieren via Datei..."); update_menu.add(updatedb_item); update_menu.add(choosedb_item); if (Utilities.appLanguage().equals("fr")) { updatedb_item.setText("Tlcharger la banque de donnes..."); updatedb_item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, ActionEvent.CTRL_MASK)); choosedb_item.setText("Ajourner la banque de donnes..."); } // -- Menu "Hilfe" -- JMenu hilfe_menu = new JMenu("Hilfe"); if (Utilities.appLanguage().equals("fr")) hilfe_menu.setText("Aide"); menu_bar.add(hilfe_menu); JMenuItem about_item = new JMenuItem("ber " + Constants.APP_NAME + "..."); JMenuItem ywesee_item = new JMenuItem(Constants.APP_NAME + " im Internet"); if (Utilities.appCustomization().equals("meddrugs")) ywesee_item.setText("med-drugs im Internet"); JMenuItem report_item = new JMenuItem("Error Report..."); JMenuItem contact_item = new JMenuItem("Kontakt..."); if (Utilities.appLanguage().equals("fr")) { // Extrawunsch med-drugs if (Utilities.appCustomization().equals("meddrugs")) about_item.setText(Constants.APP_NAME); else about_item.setText("A propos de " + Constants.APP_NAME + "..."); contact_item.setText("Contact..."); if (Utilities.appCustomization().equals("meddrugs")) ywesee_item.setText("med-drugs sur Internet"); else ywesee_item.setText(Constants.APP_NAME + " sur Internet"); report_item.setText("Rapport d'erreur..."); } hilfe_menu.add(about_item); hilfe_menu.add(ywesee_item); hilfe_menu.addSeparator(); hilfe_menu.add(report_item); hilfe_menu.addSeparator(); hilfe_menu.add(contact_item); // Menu "Abonnieren" (only for ywesee) JMenu subscribe_menu = new JMenu("Abonnieren"); if (Utilities.appLanguage().equals("fr")) subscribe_menu.setText("Abonnement"); if (Utilities.appCustomization().equals("ywesee")) { menu_bar.add(subscribe_menu); } jframe.setJMenuBar(menu_bar); // ------ Setup toolbar ------ JToolBar toolBar = new JToolBar("Database"); toolBar.setPreferredSize(new Dimension(jframe.getWidth(), 64)); final JToggleButton selectAipsButton = new JToggleButton( new ImageIcon(Constants.IMG_FOLDER + "aips32x32_bright.png")); final JToggleButton selectFavoritesButton = new JToggleButton( new ImageIcon(Constants.IMG_FOLDER + "favorites32x32_bright.png")); final JToggleButton selectInteractionsButton = new JToggleButton( new ImageIcon(Constants.IMG_FOLDER + "interactions32x32_bright.png")); final JToggleButton selectShoppingCartButton = new JToggleButton( new ImageIcon(Constants.IMG_FOLDER + "shoppingcart32x32_bright.png")); final JToggleButton selectComparisonCartButton = new JToggleButton( new ImageIcon(Constants.IMG_FOLDER + "comparisoncart32x32_bright.png")); final JToggleButton list_of_buttons[] = { selectAipsButton, selectFavoritesButton, selectInteractionsButton, selectShoppingCartButton, selectComparisonCartButton }; if (Utilities.appLanguage().equals("de")) { setupButton(selectAipsButton, "Kompendium", "aips32x32_gray.png", "aips32x32_dark.png"); setupButton(selectFavoritesButton, "Favoriten", "favorites32x32_gray.png", "favorites32x32_dark.png"); setupButton(selectInteractionsButton, "Interaktionen", "interactions32x32_gray.png", "interactions32x32_dark.png"); setupButton(selectShoppingCartButton, "Warenkorb", "shoppingcart32x32_gray.png", "shoppingcart32x32_dark.png"); setupButton(selectComparisonCartButton, "Preisvergleich", "comparisoncart32x32_gray.png", "comparisoncart32x32_dark.png"); } else if (Utilities.appLanguage().equals("fr")) { setupButton(selectAipsButton, "Compendium", "aips32x32_gray.png", "aips32x32_dark.png"); setupButton(selectFavoritesButton, "Favorites", "favorites32x32_gray.png", "favorites32x32_dark.png"); setupButton(selectInteractionsButton, "Interactions", "interactions32x32_gray.png", "interactions32x32_dark.png"); setupButton(selectShoppingCartButton, "Panier", "shoppingcart32x32_gray.png", "shoppingcart32x32_dark.png"); setupButton(selectComparisonCartButton, "Preisvergleich", "comparisoncart32x32_gray.png", "comparisoncart32x32_dark.png"); } // Add to toolbar and set up toolBar.setBackground(m_toolbar_bg); toolBar.add(selectAipsButton); toolBar.addSeparator(); toolBar.add(selectFavoritesButton); toolBar.addSeparator(); toolBar.add(selectInteractionsButton); if (!Utilities.appCustomization().equals("zurrose")) { toolBar.addSeparator(); toolBar.add(selectShoppingCartButton); } if (Utilities.appCustomization().equals("zurrorse")) { toolBar.addSeparator(); toolBar.add(selectComparisonCartButton); } toolBar.setRollover(true); toolBar.setFloatable(false); // Progress indicator (not working...) toolBar.addSeparator(new Dimension(32, 32)); toolBar.add(m_progress_indicator); // ------ Setup settingspage ------ final SettingsPage settingsPage = new SettingsPage(jframe, m_rb); // Attach observer to it settingsPage.addObserver(new Observer() { public void update(Observable o, Object arg) { System.out.println(arg); if (m_shopping_cart != null) { // Refresh some stuff m_shopping_basket.clear(); int index = m_shopping_cart.getCartIndex(); if (index > 0) m_web_panel.saveShoppingCartWithIndex(index); m_web_panel.updateShoppingHtml(); } } }); jframe.addWindowListener(new WindowListener() { // Use WindowAdapter! @Override public void windowOpened(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { m_web_panel.dispose(); Runtime.getRuntime().exit(0); } @Override public void windowClosing(WindowEvent e) { // Save shopping cart int index = m_shopping_cart.getCartIndex(); if (index > 0 && m_web_panel != null) m_web_panel.saveShoppingCartWithIndex(index); } @Override public void windowIconified(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowActivated(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } }); print_item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { m_web_panel.print(); } }); settings_item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { settingsPage.display(); } }); quit_item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { try { // Save shopping cart int index = m_shopping_cart.getCartIndex(); if (index > 0 && m_web_panel != null) m_web_panel.saveShoppingCartWithIndex(index); // Save settings WindowSaver.saveSettings(); m_web_panel.dispose(); Runtime.getRuntime().exit(0); } catch (Exception e) { System.out.println(e); } } }); subscribe_menu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent event) { if (Utilities.appCustomization().equals("ywesee")) { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI( "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=3UM84Z6WLFKZE")); } catch (IOException e) { // TODO: } catch (URISyntaxException r) { // TODO: } } } } @Override public void menuDeselected(MenuEvent event) { // do nothing } @Override public void menuCanceled(MenuEvent event) { // do nothing } }); contact_item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (Utilities.appCustomization().equals("ywesee")) { if (Desktop.isDesktopSupported()) { try { URI mail_to_uri = URI .create("mailto:zdavatz@ywesee.com?subject=AmiKo%20Desktop%20Feedback"); Desktop.getDesktop().mail(mail_to_uri); } catch (IOException e) { // TODO: } } else { AmiKoDialogs cd = new AmiKoDialogs(Utilities.appLanguage(), Utilities.appCustomization()); cd.ContactDialog(); } } else if (Utilities.appCustomization().equals("desitin")) { if (Desktop.isDesktopSupported()) { try { URI mail_to_uri = URI .create("mailto:info@desitin.ch?subject=AmiKo%20Desktop%20Desitin%20Feedback"); Desktop.getDesktop().mail(mail_to_uri); } catch (IOException e) { // TODO: } } else { AmiKoDialogs cd = new AmiKoDialogs(Utilities.appLanguage(), Utilities.appCustomization()); cd.ContactDialog(); } } else if (Utilities.appCustomization().equals("meddrugs")) { if (Desktop.isDesktopSupported()) { try { URI mail_to_uri = URI.create( "mailto:med-drugs@just-medical.com?subject=med-drugs%20desktop%20Feedback"); Desktop.getDesktop().mail(mail_to_uri); } catch (IOException e) { // TODO: } } else { AmiKoDialogs cd = new AmiKoDialogs(Utilities.appLanguage(), Utilities.appCustomization()); cd.ContactDialog(); } } else if (Utilities.appCustomization().equals("zurrose")) { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI("www.zurrose.ch/amiko")); } catch (IOException e) { // TODO: } catch (URISyntaxException r) { // TODO: } } } } }); report_item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { // Check first m_application_folder otherwise resort to // pre-installed report String report_file = m_application_data_folder + "\\" + Constants.DEFAULT_AMIKO_REPORT_BASE + Utilities.appLanguage() + ".html"; if (!(new File(report_file)).exists()) report_file = System.getProperty("user.dir") + "/dbs/" + Constants.DEFAULT_AMIKO_REPORT_BASE + Utilities.appLanguage() + ".html"; // Open report file in browser if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new File(report_file).toURI()); } catch (IOException e) { // TODO: } } } }); ywesee_item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (Utilities.appCustomization().equals("ywesee")) { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI("http://www.ywesee.com/AmiKo/Desktop")); } catch (IOException e) { // TODO: } catch (URISyntaxException r) { // TODO: } } } else if (Utilities.appCustomization().equals("desitin")) { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse( new URI("http://www.desitin.ch/produkte/arzneimittel-kompendium-apps/")); } catch (IOException e) { // TODO: } catch (URISyntaxException r) { // TODO: } } } else if (Utilities.appCustomization().equals("meddrugs")) { if (Desktop.isDesktopSupported()) { try { if (Utilities.appLanguage().equals("de")) Desktop.getDesktop().browse(new URI("http://www.med-drugs.ch")); else if (Utilities.appLanguage().equals("fr")) Desktop.getDesktop() .browse(new URI("http://www.med-drugs.ch/index.cfm?&newlang=fr")); } catch (IOException e) { // TODO: } catch (URISyntaxException r) { // TODO: } } } else if (Utilities.appCustomization().equals("zurrose")) { if (Desktop.isDesktopSupported()) { try { Desktop.getDesktop().browse(new URI("www.zurrose.ch/amiko")); } catch (IOException e) { // TODO: } catch (URISyntaxException r) { // TODO: } } } } }); about_item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { AmiKoDialogs ad = new AmiKoDialogs(Utilities.appLanguage(), Utilities.appCustomization()); ad.AboutDialog(); } }); // Container final Container container = jframe.getContentPane(); container.setBackground(Color.WHITE); container.setLayout(new BorderLayout()); // ==== Toolbar ===== container.add(toolBar, BorderLayout.NORTH); // ==== Left panel ==== JPanel left_panel = new JPanel(); left_panel.setBackground(Color.WHITE); left_panel.setLayout(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.BOTH; gbc.anchor = GridBagConstraints.CENTER; gbc.insets = new Insets(2, 2, 2, 2); // ---- Search field ---- final SearchField searchField = new SearchField("Suche Prparat"); if (Utilities.appLanguage().equals("fr")) searchField.setText("Recherche Specialit"); gbc.gridx = 0; gbc.gridy = 0; gbc.gridwidth = gbc.gridheight = 1; gbc.weightx = gbc.weighty = 0.0; // --> container.add(searchField, gbc); left_panel.add(searchField, gbc); // ---- Buttons ---- // Names String l_title = "Prparat"; String l_author = "Inhaberin"; String l_atccode = "Wirkstoff / ATC Code"; String l_regnr = "Zulassungsnummer"; String l_ingredient = "Wirkstoff"; String l_therapy = "Therapie"; String l_search = "Suche"; if (Utilities.appLanguage().equals("fr")) { l_title = "Spcialit"; l_author = "Titulaire"; l_atccode = "Principe Active / Code ATC"; l_regnr = "Nombre Enregistration"; l_ingredient = "Principe Active"; l_therapy = "Thrapie"; l_search = "Recherche"; } ButtonGroup bg = new ButtonGroup(); JToggleButton but_title = new JToggleButton(l_title); setupToggleButton(but_title); bg.add(but_title); gbc.gridx = 0; gbc.gridy = 1; gbc.gridwidth = gbc.gridheight = 1; gbc.weightx = gbc.weighty = 0.0; // --> container.add(but_title, gbc); left_panel.add(but_title, gbc); JToggleButton but_auth = new JToggleButton(l_author); setupToggleButton(but_auth); bg.add(but_auth); gbc.gridx = 0; gbc.gridy += 1; gbc.gridwidth = gbc.gridheight = 1; gbc.weightx = gbc.weighty = 0.0; // --> container.add(but_auth, gbc); left_panel.add(but_auth, gbc); JToggleButton but_atccode = new JToggleButton(l_atccode); setupToggleButton(but_atccode); bg.add(but_atccode); gbc.gridx = 0; gbc.gridy += 1; gbc.gridwidth = gbc.gridheight = 1; gbc.weightx = gbc.weighty = 0.0; // --> container.add(but_atccode, gbc); left_panel.add(but_atccode, gbc); JToggleButton but_regnr = new JToggleButton(l_regnr); setupToggleButton(but_regnr); bg.add(but_regnr); gbc.gridx = 0; gbc.gridy += 1; gbc.gridwidth = gbc.gridheight = 1; gbc.weightx = gbc.weighty = 0.0; // --> container.add(but_regnr, gbc); left_panel.add(but_regnr, gbc); JToggleButton but_therapy = new JToggleButton(l_therapy); setupToggleButton(but_therapy); bg.add(but_therapy); gbc.gridx = 0; gbc.gridy += 1; gbc.gridwidth = gbc.gridheight = 1; gbc.weightx = gbc.weighty = 0.0; // --> container.add(but_therapy, gbc); left_panel.add(but_therapy, gbc); // ---- Card layout ---- final CardLayout cardl = new CardLayout(); cardl.setHgap(-4); // HACK to make things look better!! final JPanel p_results = new JPanel(cardl); m_list_titles = new ListPanel(); m_list_auths = new ListPanel(); m_list_regnrs = new ListPanel(); m_list_atccodes = new ListPanel(); m_list_ingredients = new ListPanel(); m_list_therapies = new ListPanel(); // Contraints gbc.fill = GridBagConstraints.BOTH; gbc.gridx = 0; gbc.gridy += 1; gbc.gridwidth = 1; gbc.gridheight = 10; gbc.weightx = 1.0; gbc.weighty = 1.0; // p_results.add(m_list_titles, l_title); p_results.add(m_list_auths, l_author); p_results.add(m_list_regnrs, l_regnr); p_results.add(m_list_atccodes, l_atccode); p_results.add(m_list_ingredients, l_ingredient); p_results.add(m_list_therapies, l_therapy); // --> container.add(p_results, gbc); left_panel.add(p_results, gbc); left_panel.setBorder(null); // First card to show cardl.show(p_results, l_title); // ==== Right panel ==== JPanel right_panel = new JPanel(); right_panel.setBackground(Color.WHITE); right_panel.setLayout(new GridBagLayout()); // ---- Section titles ---- m_section_titles = null; if (Utilities.appLanguage().equals("de")) { m_section_titles = new IndexPanel(SectionTitle_DE); } else if (Utilities.appLanguage().equals("fr")) { m_section_titles = new IndexPanel(SectionTitle_FR); } m_section_titles.setMinimumSize(new Dimension(150, 150)); m_section_titles.setMaximumSize(new Dimension(320, 1000)); // ---- Fachinformation ---- m_web_panel = new WebPanel2(); m_web_panel.setMinimumSize(new Dimension(320, 150)); // Add JSplitPane on the RIGHT final int Divider_location = 150; final int Divider_size = 10; final JSplitPane split_pane_right = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, m_section_titles, m_web_panel); split_pane_right.setOneTouchExpandable(true); split_pane_right.setDividerLocation(Divider_location); split_pane_right.setDividerSize(Divider_size); // Add JSplitPane on the LEFT JSplitPane split_pane_left = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, left_panel, split_pane_right /* right_panel */); split_pane_left.setOneTouchExpandable(true); split_pane_left.setDividerLocation(320); // Sets the pane divider location split_pane_left.setDividerSize(Divider_size); container.add(split_pane_left, BorderLayout.CENTER); // Add status bar on the bottom JPanel statusPanel = new JPanel(); statusPanel.setPreferredSize(new Dimension(jframe.getWidth(), 16)); statusPanel.setLayout(new BoxLayout(statusPanel, BoxLayout.X_AXIS)); container.add(statusPanel, BorderLayout.SOUTH); final JLabel m_status_label = new JLabel(""); m_status_label.setHorizontalAlignment(SwingConstants.LEFT); statusPanel.add(m_status_label); // Add mouse listener searchField.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { searchField.setText(""); } }); final String final_title = l_title; final String final_author = l_author; final String final_atccode = l_atccode; final String final_regnr = l_regnr; final String final_therapy = l_therapy; final String final_search = l_search; // Internal class that implements switching between buttons final class Toggle { public void toggleButton(JToggleButton jbn) { for (int i = 0; i < list_of_buttons.length; ++i) { if (jbn == list_of_buttons[i]) list_of_buttons[i].setSelected(true); else list_of_buttons[i].setSelected(false); } } } ; // ------ Add toolbar action listeners ------ selectAipsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { new Toggle().toggleButton(selectAipsButton); // Set state 'aips' if (!m_curr_uistate.getUseMode().equals("aips")) { m_curr_uistate.setUseMode("aips"); // Show middle pane split_pane_right.setDividerSize(Divider_size); split_pane_right.setDividerLocation(Divider_location); m_section_titles.setVisible(true); // SwingUtilities.invokeLater(new Runnable() { @Override public void run() { m_start_time = System.currentTimeMillis(); m_query_str = searchField.getText(); int num_hits = retrieveAipsSearchResults(false); m_status_label.setText(med_search.size() + " Suchresultate in " + (System.currentTimeMillis() - m_start_time) / 1000.0f + " Sek."); // if (med_index < 0 && prev_med_index >= 0) med_index = prev_med_index; m_web_panel.updateText(); if (num_hits == 0) { m_web_panel.emptyPage(); } } }); } } }); selectFavoritesButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { new Toggle().toggleButton(selectFavoritesButton); // Set state 'favorites' if (!m_curr_uistate.getUseMode().equals("favorites")) { m_curr_uistate.setUseMode("favorites"); // Show middle pane split_pane_right.setDividerSize(Divider_size); split_pane_right.setDividerLocation(Divider_location); m_section_titles.setVisible(true); // SwingUtilities.invokeLater(new Runnable() { @Override public void run() { m_start_time = System.currentTimeMillis(); // m_query_str = searchField.getText(); // Clear the search container med_search.clear(); for (String regnr : favorite_meds_set) { List<Medication> meds = m_sqldb.searchRegNr(regnr); if (!meds.isEmpty()) { // Add med database ID med_search.add(meds.get(0)); } } // Sort list of meds Collections.sort(med_search, new Comparator<Medication>() { @Override public int compare(final Medication m1, final Medication m2) { return m1.getTitle().compareTo(m2.getTitle()); } }); sTitle(); cardl.show(p_results, final_title); m_status_label.setText(med_search.size() + " Suchresultate in " + (System.currentTimeMillis() - m_start_time) / 1000.0f + " Sek."); } }); } } }); selectInteractionsButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { new Toggle().toggleButton(selectInteractionsButton); // Set state 'interactions' if (!m_curr_uistate.getUseMode().equals("interactions")) { m_curr_uistate.setUseMode("interactions"); // Show middle pane split_pane_right.setDividerSize(Divider_size); split_pane_right.setDividerLocation(Divider_location); m_section_titles.setVisible(true); // SwingUtilities.invokeLater(new Runnable() { @Override public void run() { m_query_str = searchField.getText(); retrieveAipsSearchResults(false); // Switch to interaction mode m_web_panel.updateInteractionsCart(); m_web_panel.repaint(); m_web_panel.validate(); } }); } } }); selectShoppingCartButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String email_adr = m_prefs.get("emailadresse", ""); if (email_adr != null && email_adr.length() > 2) // Two chars is the minimum lenght for an email address m_preferences_ok = true; if (m_preferences_ok) { m_preferences_ok = false; // Check always new Toggle().toggleButton(selectShoppingCartButton); // Set state 'shopping' if (!m_curr_uistate.getUseMode().equals("shopping")) { m_curr_uistate.setUseMode("shopping"); // Show middle pane split_pane_right.setDividerSize(Divider_size); split_pane_right.setDividerLocation(Divider_location); m_section_titles.setVisible(true); // Set right panel title m_web_panel.setTitle(m_rb.getString("shoppingCart")); // Switch to shopping cart int index = 1; if (m_shopping_cart != null) { index = m_shopping_cart.getCartIndex(); m_web_panel.loadShoppingCartWithIndex(index); // m_shopping_cart.printShoppingBasket(); } // m_web_panel.updateShoppingHtml(); m_web_panel.updateListOfPackages(); if (m_first_pass == true) { m_first_pass = false; if (Utilities.appCustomization().equals("ywesee")) med_search = m_sqldb.searchAuth("ibsa"); else if (Utilities.appCustomization().equals("desitin")) med_search = m_sqldb.searchAuth("desitin"); sAuth(); cardl.show(p_results, final_author); } } } else { selectShoppingCartButton.setSelected(false); settingsPage.display(); } } }); selectComparisonCartButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { new Toggle().toggleButton(selectComparisonCartButton); // Set state 'comparison' if (!m_curr_uistate.getUseMode().equals("comparison")) { m_curr_uistate.setUseMode("comparison"); // Hide middle pane m_section_titles.setVisible(false); split_pane_right.setDividerLocation(0); split_pane_right.setDividerSize(0); // SwingUtilities.invokeLater(new Runnable() { @Override public void run() { m_start_time = System.currentTimeMillis(); // Set right panel title m_web_panel.setTitle(getTitle("priceComp")); if (med_index >= 0) { if (med_id != null && med_index < med_id.size()) { Medication m = m_sqldb.getMediWithId(med_id.get(med_index)); String atc_code = m.getAtcCode(); if (atc_code != null) { String atc = atc_code.split(";")[0]; m_web_panel.fillComparisonBasket(atc); m_web_panel.updateComparisonCartHtml(); // Update pane on the left retrieveAipsSearchResults(false); } } } m_status_label.setText(rose_search.size() + " Suchresultate in " + (System.currentTimeMillis() - m_start_time) / 1000.0f + " Sek."); } }); } } }); // ------ Add keylistener to text field (type as you go feature) ------ searchField.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent e) { // keyReleased(KeyEvent e) // invokeLater potentially in the wrong place... more testing // required SwingUtilities.invokeLater(new Runnable() { @Override public void run() { if (m_curr_uistate.isLoadCart()) m_curr_uistate.restoreUseMode(); m_start_time = System.currentTimeMillis(); m_query_str = searchField.getText(); // Queries for SQLite DB if (!m_query_str.isEmpty()) { if (m_query_type == 0) { if (m_curr_uistate.isComparisonMode()) { rose_search = m_rosedb.searchTitle(m_query_str); } else { med_search = m_sqldb.searchTitle(m_query_str); if (m_curr_uistate.databaseUsed().equals("favorites")) retrieveFavorites(); } sTitle(); cardl.show(p_results, final_title); } else if (m_query_type == 1) { if (m_curr_uistate.isComparisonMode()) { rose_search = m_rosedb.searchSupplier(m_query_str); } else { med_search = m_sqldb.searchAuth(m_query_str); if (m_curr_uistate.databaseUsed().equals("favorites")) retrieveFavorites(); } sAuth(); cardl.show(p_results, final_author); } else if (m_query_type == 2) { if (m_curr_uistate.isComparisonMode()) { rose_search = m_rosedb.searchATC(m_query_str); } else { med_search = m_sqldb.searchATC(m_query_str); if (m_curr_uistate.databaseUsed().equals("favorites")) retrieveFavorites(); } sATC(); cardl.show(p_results, final_atccode); } else if (m_query_type == 3) { if (m_curr_uistate.isComparisonMode()) { rose_search = m_rosedb.searchEan(m_query_str); } else { med_search = m_sqldb.searchRegNr(m_query_str); if (m_curr_uistate.databaseUsed().equals("favorites")) retrieveFavorites(); } sRegNr(); cardl.show(p_results, final_regnr); } else if (m_query_type == 4) { if (m_curr_uistate.isComparisonMode()) { rose_search = m_rosedb.searchTherapy(m_query_str); } else { med_search = m_sqldb.searchApplication(m_query_str); if (m_curr_uistate.databaseUsed().equals("favorites")) retrieveFavorites(); } sTherapy(); cardl.show(p_results, final_therapy); } else { // do nothing } int num_hits = 0; if (m_curr_uistate.isComparisonMode()) num_hits = rose_search.size(); else num_hits = med_search.size(); m_status_label.setText(num_hits + " Suchresultate in " + (System.currentTimeMillis() - m_start_time) / 1000.0f + " Sek."); } } }); } }); // Add actionlisteners but_title.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (m_curr_uistate.isLoadCart()) m_curr_uistate.restoreUseMode(); searchField.setText(final_search + " " + final_title); m_curr_uistate.setQueryType(m_query_type = 0); sTitle(); cardl.show(p_results, final_title); } }); but_auth.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (m_curr_uistate.isLoadCart()) m_curr_uistate.restoreUseMode(); searchField.setText(final_search + " " + final_author); m_curr_uistate.setQueryType(m_query_type = 1); sAuth(); cardl.show(p_results, final_author); } }); but_atccode.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (m_curr_uistate.isLoadCart()) m_curr_uistate.restoreUseMode(); searchField.setText(final_search + " " + final_atccode); m_curr_uistate.setQueryType(m_query_type = 2); sATC(); cardl.show(p_results, final_atccode); } }); but_regnr.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (m_curr_uistate.isLoadCart()) m_curr_uistate.restoreUseMode(); searchField.setText(final_search + " " + final_regnr); m_curr_uistate.setQueryType(m_query_type = 3); sRegNr(); cardl.show(p_results, final_regnr); } }); but_therapy.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if (m_curr_uistate.isLoadCart()) m_curr_uistate.restoreUseMode(); searchField.setText(final_search + " " + final_therapy); m_curr_uistate.setQueryType(m_query_type = 4); sTherapy(); cardl.show(p_results, final_therapy); } }); // Display window jframe.pack(); // jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jframe.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); // jframe.setAlwaysOnTop(true); jframe.setVisible(true); // Check if user has selected an alternative database /* * NOTE: 21/11/2013: This solution is put on ice. Favored is a solution * where the database selected by the user is saved in a default folder * (see variable "m_application_data_folder") */ /* * try { WindowSaver.loadSettings(jframe); String database_path = * WindowSaver.getDbPath(); if (database_path!=null) * m_sqldb.loadDBFromPath(database_path); } catch(IOException e) { * e.printStackTrace(); } */ // Load AIPS database selectAipsButton.setSelected(true); selectFavoritesButton.setSelected(false); m_curr_uistate.setUseMode("aips"); med_search = m_sqldb.searchTitle(""); sTitle(); // Used instead of sTitle (which is slow) cardl.show(p_results, final_title); // Add menu item listeners updatedb_item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { if (m_mutex_update == false) { m_mutex_update = true; String db_file = m_maindb_update.doIt(jframe, Utilities.appLanguage(), Utilities.appCustomization(), m_application_data_folder, m_full_db_update); // ... and update time if (m_full_db_update == true) { DateTime dT = new DateTime(); m_prefs.put("updateTime", dT.now().toString()); } // if (!db_file.isEmpty()) { // Save db path (can't hurt) WindowSaver.setDbPath(db_file); } } } }); choosedb_item.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { String db_file = m_maindb_update.chooseFromFile(jframe, Utilities.appLanguage(), Utilities.appCustomization(), m_application_data_folder); // ... and update time DateTime dT = new DateTime(); m_prefs.put("updateTime", dT.now().toString()); // if (!db_file.isEmpty()) { // Save db path (can't hurt) WindowSaver.setDbPath(db_file); } } }); /** * Observers */ // Attach observer to 'm_update' m_maindb_update.addObserver(new Observer() { @Override public void update(Observable o, Object arg) { System.out.println(arg); // Reset flag m_full_db_update = true; m_mutex_update = false; // Refresh some stuff after update loadAuthors(); m_emailer.loadMap(); settingsPage.load_gln_codes(); if (m_shopping_cart != null) { m_shopping_cart.load_conditions(); m_shopping_cart.load_glns(); } // Empty shopping basket if (m_curr_uistate.isShoppingMode()) { m_shopping_basket.clear(); int index = m_shopping_cart.getCartIndex(); if (index > 0) m_web_panel.saveShoppingCartWithIndex(index); m_web_panel.updateShoppingHtml(); } if (m_curr_uistate.isComparisonMode()) m_web_panel.setTitle(getTitle("priceComp")); } }); // Attach observer to 'm_emailer' m_emailer.addObserver(new Observer() { @Override public void update(Observable o, Object arg) { System.out.println(arg); // Empty shopping basket m_shopping_basket.clear(); int index = m_shopping_cart.getCartIndex(); if (index > 0) m_web_panel.saveShoppingCartWithIndex(index); m_web_panel.updateShoppingHtml(); } }); // Attach observer to "m_comparison_cart" m_comparison_cart.addObserver(new Observer() { @Override public void update(Observable o, Object arg) { System.out.println(arg); m_web_panel.setTitle(getTitle("priceComp")); m_comparison_cart.clearUploadList(); m_web_panel.updateComparisonCartHtml(); new AmiKoDialogs(Utilities.appLanguage(), Utilities.appCustomization()).UploadDialog((String) arg); } }); // If command line options are provided start app with a particular title or eancode if (commandLineOptionsProvided()) { if (!CML_OPT_TITLE.isEmpty()) startAppWithTitle(but_title); else if (!CML_OPT_EANCODE.isEmpty()) startAppWithEancode(but_regnr); else if (!CML_OPT_REGNR.isEmpty()) startAppWithRegnr(but_regnr); } // Start timer Timer global_timer = new Timer(); // Time checks all 2 minutes (120'000 milliseconds) global_timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { checkIfUpdateRequired(updatedb_item); } }, 2 * 60 * 1000, 2 * 60 * 1000); }
From source file:fs.MainWindow.java
public void GenerateTable(Object[][] data, String title, String subtitle, final String[] titles) { JFrame window = new JFrame(title); window.setLayout(new java.awt.BorderLayout(5, 5)); JLabel label = new JLabel(subtitle); label.setFont(new java.awt.Font("Tahoma", 1, 12)); label.setForeground(new java.awt.Color(0, 0, 255)); label.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); label.setOpaque(true);/*from ww w. j a va 2 s.co m*/ label.setPreferredSize(new java.awt.Dimension(50, 30)); ListModel lm = new AbstractListModel() { String headers[] = titles; @Override public int getSize() { return headers.length; } @Override public Object getElementAt(int index) { return headers[index]; } }; // String[] titles = getClasses(); JList rowHeader = new JList(lm); rowHeader.setFixedCellWidth(50); JTable jTable = new JTable(data, titles); rowHeader.setFixedCellHeight(jTable.getRowHeight()); rowHeader.setCellRenderer(new RowHeaderRenderer(jTable)); JScrollPane scroll = new JScrollPane(jTable); scroll.setRowHeaderView(rowHeader); getContentPane().add(scroll, BorderLayout.CENTER); jTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); jTable.setAlignmentX(JTable.CENTER_ALIGNMENT); window.add(label, java.awt.BorderLayout.NORTH); window.add(scroll, java.awt.BorderLayout.CENTER); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); window.setBounds((screenSize.width - 800) / 2, (screenSize.height - 270) / 2, 800, 270); window.setVisible(true); }
From source file:de.bfs.radon.omsimulation.gui.OMPanelResults.java
/** * Initialises the interface of the results panel. */// w w w . ja v a 2 s.c o m protected void initialize() { setLayout(null); lblExportChartTo = new JLabel("Export chart to ..."); lblExportChartTo.setBounds(436, 479, 144, 14); lblExportChartTo.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); lblExportChartTo.setVisible(false); add(lblExportChartTo); btnMaximize = new JButton("Fullscreen"); btnMaximize.setBounds(10, 475, 124, 23); btnMaximize.setFont(new Font("SansSerif", Font.PLAIN, 11)); btnMaximize.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (comboBoxSimulations.isEnabled()) { if (comboBoxSimulations.getSelectedItem() != null) { JFrame chartFrame = new JFrame(); OMSimulation simulation = (OMSimulation) comboBoxSimulations.getSelectedItem(); String title = simulation.toString(); DescriptiveStatistics statistics = null; OMStatistics statisticsType = (OMStatistics) comboBoxStatistics.getSelectedItem(); OMRoomType roomType = null; switch (statisticsType) { case RoomArithmeticMeans: title = "R_AM, " + title; statistics = simulation.getRoomAmDescriptiveStats(); roomType = OMRoomType.Room; break; case RoomGeometricMeans: title = "R_GM, " + title; statistics = simulation.getRoomGmDescriptiveStats(); roomType = OMRoomType.Room; break; case RoomMedianQ50: title = "R_MED, " + title; statistics = simulation.getRoomMedDescriptiveStats(); roomType = OMRoomType.Room; break; case RoomMaxima: title = "R_MAX, " + title; statistics = simulation.getRoomMaxDescriptiveStats(); roomType = OMRoomType.Room; break; case CellarArithmeticMeans: title = "C_AM, " + title; statistics = simulation.getCellarAmDescriptiveStats(); roomType = OMRoomType.Cellar; break; case CellarGeometricMeans: title = "C_GM, " + title; statistics = simulation.getCellarGmDescriptiveStats(); roomType = OMRoomType.Cellar; break; case CellarMedianQ50: title = "C_MED, " + title; statistics = simulation.getCellarMedDescriptiveStats(); roomType = OMRoomType.Cellar; break; case CellarMaxima: title = "C_MAX, " + title; statistics = simulation.getCellarMaxDescriptiveStats(); roomType = OMRoomType.Cellar; break; default: title = "R_AM, " + title; statistics = simulation.getRoomAmDescriptiveStats(); roomType = OMRoomType.Misc; break; } JPanel chartPanel = createDistributionPanel(title, statistics, roomType, false, true, true); chartFrame.getContentPane().add(chartPanel); chartFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); chartFrame.setBounds(0, 0, (int) dim.getWidth(), (int) dim.getHeight()); chartFrame.setTitle("OM Simulation Tool: " + title); chartFrame.setResizable(true); chartFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); chartFrame.setVisible(true); } } } }); add(btnMaximize); btnCsv = new JButton("CSV"); btnCsv.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileDialog = new JFileChooser(); fileDialog.setFileFilter(new FileNameExtensionFilter("*.csv", "csv")); fileDialog.showSaveDialog(getParent()); final File file = fileDialog.getSelectedFile(); if (file != null) { String csv; String[] tmpFileName = file.getAbsolutePath().split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("csv")) { csv = ""; } else { csv = ".csv"; } String csvPath = file.getAbsolutePath() + csv; OMSimulation simulation = (OMSimulation) comboBoxSimulations.getSelectedItem(); OMCampaign[] campaigns = simulation.getCampaigns(); File csvFile = new File(csvPath); try { FileWriter logWriter = new FileWriter(csvFile); BufferedWriter csvOutput = new BufferedWriter(logWriter); OMStatistics statisticsType = (OMStatistics) comboBoxStatistics.getSelectedItem(); String head = ""; switch (statisticsType) { case RoomArithmeticMeans: head = "R_AM"; break; case RoomGeometricMeans: head = "R_GM"; break; case RoomMedianQ50: head = "R_MED"; break; case RoomMaxima: head = "R_MAX"; break; case CellarArithmeticMeans: head = "C_AM"; break; case CellarGeometricMeans: head = "C_GM"; break; case CellarMedianQ50: head = "C_MED"; break; case CellarMaxima: head = "C_MAX"; break; default: head = "R_AM"; break; } csvOutput.write("\"ID\";\"CAMPAIGN\";\"START\";\"" + head + "\""); csvOutput.newLine(); int value = 0; for (int i = 0; i < campaigns.length; i++) { switch (statisticsType) { case RoomArithmeticMeans: value = (int) campaigns[i].getRoomAverage(); break; case RoomGeometricMeans: value = (int) campaigns[i].getRoomLogAverage(); break; case RoomMedianQ50: value = (int) campaigns[i].getRoomMedian(); break; case RoomMaxima: value = (int) campaigns[i].getRoomMaximum(); break; case CellarArithmeticMeans: value = (int) campaigns[i].getCellarAverage(); break; case CellarGeometricMeans: value = (int) campaigns[i].getCellarLogAverage(); break; case CellarMedianQ50: value = (int) campaigns[i].getCellarMedian(); break; case CellarMaxima: value = (int) campaigns[i].getCellarMaximum(); break; default: value = (int) campaigns[i].getRoomAverage(); break; } csvOutput.write("\"" + i + "\";\"" + campaigns[i].getVariation() + "\";\"" + campaigns[i].getStart() + "\";\"" + value + "\""); csvOutput.newLine(); } JOptionPane.showMessageDialog(null, "CSV saved successfully!\n" + csvPath, "Success", JOptionPane.INFORMATION_MESSAGE); csvOutput.close(); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Failed to write CSV. Please check permissions!\n" + ioe.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE); ioe.printStackTrace(); } } else { JOptionPane.showMessageDialog(null, "Failed to write CSV. Please check the file path!", "Failed", JOptionPane.ERROR_MESSAGE); } } }); btnCsv.setBounds(590, 475, 70, 23); btnCsv.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); btnCsv.setVisible(false); add(btnCsv); btnPdf = new JButton("PDF"); btnPdf.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { JFileChooser fileDialog = new JFileChooser(); fileDialog.setFileFilter(new FileNameExtensionFilter("*.pdf", "pdf")); fileDialog.showSaveDialog(getParent()); final File file = fileDialog.getSelectedFile(); if (file != null) { String pdf; String[] tmpFileName = file.getAbsolutePath().split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("pdf")) { pdf = ""; } else { pdf = ".pdf"; } String pdfPath = file.getAbsolutePath() + pdf; OMSimulation simulation = (OMSimulation) comboBoxSimulations.getSelectedItem(); String title = simulation.toString(); DescriptiveStatistics statistics = null; OMStatistics statisticsType = (OMStatistics) comboBoxStatistics.getSelectedItem(); OMRoomType roomType = null; switch (statisticsType) { case RoomArithmeticMeans: title = "R_AM, " + title; statistics = simulation.getRoomAmDescriptiveStats(); roomType = OMRoomType.Room; break; case RoomGeometricMeans: title = "R_GM, " + title; statistics = simulation.getRoomGmDescriptiveStats(); roomType = OMRoomType.Room; break; case RoomMedianQ50: title = "R_MED, " + title; statistics = simulation.getRoomMedDescriptiveStats(); roomType = OMRoomType.Room; break; case RoomMaxima: title = "R_MAX, " + title; statistics = simulation.getRoomMaxDescriptiveStats(); roomType = OMRoomType.Room; break; case CellarArithmeticMeans: title = "C_AM, " + title; statistics = simulation.getCellarAmDescriptiveStats(); roomType = OMRoomType.Cellar; break; case CellarGeometricMeans: title = "C_GM, " + title; statistics = simulation.getCellarGmDescriptiveStats(); roomType = OMRoomType.Cellar; break; case CellarMedianQ50: title = "C_MED, " + title; statistics = simulation.getCellarMedDescriptiveStats(); roomType = OMRoomType.Cellar; break; case CellarMaxima: title = "C_MAX, " + title; statistics = simulation.getCellarMaxDescriptiveStats(); roomType = OMRoomType.Cellar; break; default: title = "R_AM, " + title; statistics = simulation.getRoomAmDescriptiveStats(); roomType = OMRoomType.Misc; break; } JFreeChart chart = OMCharts.createDistributionChart(title, statistics, roomType, false); int height = (int) PageSize.A4.getWidth(); int width = (int) PageSize.A4.getHeight(); try { OMExports.exportPdf(pdfPath, chart, width, height, new DefaultFontMapper(), title); JOptionPane.showMessageDialog(null, "PDF saved successfully!\n" + pdfPath, "Success", JOptionPane.INFORMATION_MESSAGE); } catch (IOException ioe) { JOptionPane.showMessageDialog(null, "Failed to write PDF. Please check permissions!\n" + ioe.getMessage(), "Failed", JOptionPane.ERROR_MESSAGE); ioe.printStackTrace(); } } else { JOptionPane.showMessageDialog(null, "Failed to write PDF. Please check the file path!", "Failed", JOptionPane.ERROR_MESSAGE); } } }); btnPdf.setBounds(670, 475, 70, 23); btnPdf.setFont(new Font(Font.SANS_SERIF, Font.PLAIN, 11)); btnPdf.setVisible(false); add(btnPdf); lblSelectSimulation = new JLabel("Select Simulation"); lblSelectSimulation.setFont(new Font("SansSerif", Font.PLAIN, 11)); lblSelectSimulation.setBounds(10, 65, 132, 14); add(lblSelectSimulation); lblSelectStatistics = new JLabel("Select Statistics"); lblSelectStatistics.setFont(new Font("SansSerif", Font.PLAIN, 11)); lblSelectStatistics.setBounds(10, 94, 132, 14); add(lblSelectStatistics); comboBoxSimulations = new JComboBox<OMSimulation>(); comboBoxSimulations.setFont(new Font("SansSerif", Font.PLAIN, 11)); comboBoxSimulations.addPropertyChangeListener(new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent arg0) { boolean b = false; if (comboBoxSimulations.isEnabled()) { if (comboBoxSimulations.getSelectedItem() != null) { b = true; comboBoxStatistics.removeAllItems(); comboBoxStatistics.setModel(new DefaultComboBoxModel<OMStatistics>(OMStatistics.values())); } else { b = false; comboBoxStatistics.removeAllItems(); } } else { b = false; comboBoxStatistics.removeAllItems(); } progressBar.setEnabled(b); btnPdf.setVisible(b); btnCsv.setVisible(b); btnMaximize.setVisible(b); lblExportChartTo.setVisible(b); comboBoxStatistics.setEnabled(b); lblSelectStatistics.setEnabled(b); } }); comboBoxSimulations.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { boolean b = false; if (comboBoxSimulations.isEnabled()) { if (comboBoxSimulations.getSelectedItem() != null) { b = true; comboBoxStatistics.removeAllItems(); comboBoxStatistics.setModel(new DefaultComboBoxModel<OMStatistics>(OMStatistics.values())); comboBoxStatistics.setSelectedIndex(0); } else { b = false; comboBoxStatistics.removeAllItems(); } } else { b = false; comboBoxStatistics.removeAllItems(); } progressBar.setEnabled(b); btnPdf.setVisible(b); btnCsv.setVisible(b); btnMaximize.setVisible(b); lblExportChartTo.setVisible(b); comboBoxStatistics.setEnabled(b); lblSelectStatistics.setEnabled(b); } }); comboBoxSimulations.setBounds(152, 61, 454, 22); add(comboBoxSimulations); btnRefresh = new JButton("Load"); btnRefresh.setFont(new Font("SansSerif", Font.PLAIN, 11)); btnRefresh.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (txtOmsFile.getText() != null && !txtOmsFile.getText().equals("") && !txtOmsFile.getText().equals(" ")) { txtOmsFile.setBackground(Color.WHITE); String omsPath = txtOmsFile.getText(); String oms; String[] tmpFileName = omsPath.split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("oms")) { oms = ""; } else { oms = ".oms"; } txtOmsFile.setText(omsPath + oms); setOmsFile(omsPath + oms); File omsFile = new File(omsPath + oms); if (omsFile.exists()) { txtOmsFile.setBackground(Color.WHITE); btnRefresh.setEnabled(false); comboBoxSimulations.setEnabled(false); setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); progressBar.setStringPainted(true); progressBar.setVisible(true); progressBar.setIndeterminate(true); btnPdf.setVisible(false); btnCsv.setVisible(false); btnMaximize.setVisible(false); lblExportChartTo.setVisible(false); refreshSimulationsTask = new RefreshSimulations(); refreshSimulationsTask.execute(); } else { txtOmsFile.setBackground(new Color(255, 222, 222, 128)); JOptionPane.showMessageDialog(null, "OMS-file not found, please check the file path!", "Error", JOptionPane.ERROR_MESSAGE); } } else { txtOmsFile.setBackground(new Color(255, 222, 222, 128)); JOptionPane.showMessageDialog(null, "Please select an OMS-file!", "Warning", JOptionPane.WARNING_MESSAGE); } } }); comboBoxStatistics = new JComboBox<OMStatistics>(); comboBoxStatistics.setFont(new Font("SansSerif", Font.PLAIN, 11)); comboBoxStatistics.setBounds(152, 90, 454, 22); comboBoxStatistics.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { updateDistribution(); } }); add(comboBoxStatistics); btnRefresh.setBounds(616, 61, 124, 23); add(btnRefresh); panelDistribution = new JPanel(); panelDistribution.setBounds(10, 118, 730, 347); add(panelDistribution); progressBar = new JProgressBar(); progressBar.setFont(new Font("SansSerif", Font.PLAIN, 11)); progressBar.setBounds(10, 475, 730, 23); add(progressBar); progressBar.setEnabled(false); comboBoxStatistics.setEnabled(false); lblSelectStatistics.setEnabled(false); btnPdf.setVisible(false); btnCsv.setVisible(false); btnMaximize.setVisible(false); lblExportChartTo.setVisible(false); lblHelp = new JLabel("Select an OMS-Simulation file to analyse the simulation results and " + "display the distribution chart."); lblHelp.setForeground(Color.GRAY); lblHelp.setFont(new Font("SansSerif", Font.PLAIN, 11)); lblHelp.setBounds(10, 10, 730, 14); add(lblHelp); lblSelectOms = new JLabel("Open OMS-File"); lblSelectOms.setFont(new Font("SansSerif", Font.PLAIN, 11)); lblSelectOms.setBounds(10, 36, 132, 14); add(lblSelectOms); txtOmsFile = new JTextField(); txtOmsFile.addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { setOmsFile(txtOmsFile.getText()); } }); txtOmsFile.setFont(new Font("SansSerif", Font.PLAIN, 11)); txtOmsFile.setColumns(10); txtOmsFile.setBounds(152, 33, 454, 20); add(txtOmsFile); buttonBrowse = new JButton("Browse"); buttonBrowse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { JFileChooser fileDialog = new JFileChooser(); fileDialog.setFileFilter(new FileNameExtensionFilter("*.oms", "oms")); fileDialog.showOpenDialog(getParent()); final File file = fileDialog.getSelectedFile(); if (file != null) { String oms; String[] tmpFileName = file.getAbsolutePath().split("\\."); if (tmpFileName[tmpFileName.length - 1].equals("oms")) { oms = ""; } else { oms = ".oms"; } txtOmsFile.setText(file.getAbsolutePath() + oms); setOmsFile(file.getAbsolutePath() + oms); } } }); buttonBrowse.setFont(new Font("SansSerif", Font.PLAIN, 11)); buttonBrowse.setBounds(616, 32, 124, 23); add(buttonBrowse); progressBar.setVisible(false); }
From source file:direccion.Reportes.java
public Reportes() { String titulo = "Reportes"; jFrame = new JFrame(titulo); jFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); jFrame.setSize(800, 600);//w w w. j a v a 2 s . c om Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int x = (screenSize.width / 2) - (jFrame.getSize().width / 2); int y = (screenSize.height / 2) - (jFrame.getSize().height / 2); jFrame.setLocation(x, y); JLabel etiqueta = new JLabel("Reportes"); etiqueta.setBounds(300, 25, 200, 50); etiqueta.setFont(new Font("Verdana", Font.BOLD, 30)); etiqueta.setForeground(Color.BLACK); JMenuBar jMenuBar = new JMenuBar(); JMenu acceso = new JMenu("Acceso a"); JMenu ayuda = new JMenu("Ayuda"); JMenuItem rec_hum = new JMenuItem("Recursos Humanos"); JMenuItem conta = new JMenuItem("Contabilidad"); JMenuItem ventas = new JMenuItem("Ventas"); JMenuItem compras = new JMenuItem("Compras"); JMenuItem inventario = new JMenuItem("Inventario"); JMenuItem acerca_de = new JMenuItem("Acerca de"); acerca_de.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JOptionPane.showMessageDialog(null, "Ayuda", "Ayuda", 3); } }); acceso.add(rec_hum); acceso.add(conta); acceso.add(ventas); acceso.add(compras); acceso.add(inventario); ayuda.add(acerca_de); jMenuBar.add(acceso); jMenuBar.add(ayuda); JCalendar cal1 = new JCalendar(); cal1.setBounds(250, 150, 400, 300); JCalendarCombo cal2 = new JCalendarCombo(); cal2.setBounds(250, 150, 400, 300); String reportes[] = { "Mantenimiento", "Compras", "Ventas", "Inventario", "Contabilidad", "Recursos Humanos" }; JComboBox combobox = new JComboBox(reportes); combobox.setBounds(300, 100, 150, 30); JLabel calendario = new JLabel("Fecha de Operacin:"); calendario.setBounds(60, 150, 150, 30); JButton aceptar = new JButton("Aceptar"); aceptar.setBounds(50, 200, 150, 30); aceptar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (combobox.getSelectedIndex() == 0) { datos_mantenimiento.setValue("Recursos Humanos", d_mant_rh); datos_mantenimiento.setValue("Contabilidad", d_mant_cont); datos_mantenimiento.setValue("Ventas", d_mant_vent); datos_mantenimiento.setValue("Compras", d_mant_comp); datos_mantenimiento.setValue("Inventario", d_mant_inv); datos_mantenimiento.setValue("Mantenimiento", d_mant_mant); Grafica = ChartFactory.createPieChart3D("Mantenimiento", datos_mantenimiento, true, true, true); ChartPanel panel_grafica = new ChartPanel(Grafica); JFrame frame_grafica = new JFrame("Grfico"); JMenuBar menu = new JMenuBar(); JMenu archivo = new JMenu("Archivo"); JMenuItem guardar = new JMenuItem("Guardar como reporte..."); guardar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Document document = new Document(); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, new FileOutputStream("Grfico Mantenimiento.pdf")); } catch (DocumentException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(450, 450); Graphics2D g2 = tp.createGraphicsShapes(450, 450); menu.setVisible(false); frame_grafica.print(g2); menu.setVisible(true); g2.dispose(); cb.addTemplate(tp, 30, 400); document.close(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Reporte de Mantenimiento"); Row fila = sheet.createRow(0); File archivo = new File("Reporte de Mantenimiento.xls"); Cell celda; String[] titulos = { "Recursos Humanos", "Contabilidad", "Ventas", "Compras", "Inventario", "Mantenimiento" }; Double[] datos = { d_mant_rh, d_mant_cont, d_mant_vent, d_mant_comp, d_mant_inv, d_mant_mant }; int i; for (i = 0; i < titulos.length; i++) { celda = fila.createCell(i); celda.setCellValue(titulos[i]); } fila = sheet.createRow(1); for (i = 0; i < datos.length; i++) { celda = fila.createCell(i); celda.setCellValue(datos[i]); } try { FileOutputStream out = new FileOutputStream(archivo); workbook.write(out); out.close(); System.out.println("Archivo creado exitosamente!"); } catch (IOException ex) { System.out.println("Error de escritura"); ex.printStackTrace(); } } }); archivo.add(guardar); menu.add(archivo); frame_grafica.getContentPane().add(panel_grafica); frame_grafica.setBounds(60, 60, 450, 400); frame_grafica.setJMenuBar(menu); frame_grafica.setVisible(true); frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } if (combobox.getSelectedIndex() == 1) { datos_compras.setValue("Nomina", d_comp_nom); datos_compras.setValue("Compras", d_comp_comp); datos_compras.setValue("Gastos Fijos", d_comp_gf); datos_compras.setValue("Gastos Variables", d_comp_gv); datos_compras.setValue("Gastos Otros", d_comp_go); Grafica = ChartFactory.createPieChart3D("Compras", datos_compras, true, true, true); ChartPanel panel_grafica = new ChartPanel(Grafica); JFrame frame_grafica = new JFrame("Grfico"); JMenuBar menu = new JMenuBar(); JMenu archivo = new JMenu("Archivo"); JMenuItem guardar = new JMenuItem("Guardar como reporte..."); guardar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Document document = new Document(); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, new FileOutputStream("Grfico Compras.pdf")); } catch (DocumentException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } document.open(); menu.setVisible(false); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(450, 450); Graphics2D g2 = tp.createGraphicsShapes(850, 850); menu.setVisible(false); frame_grafica.print(g2); menu.setVisible(true); g2.dispose(); cb.addTemplate(tp, 30, 400); document.close(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Reporte de Compras"); Row fila = sheet.createRow(0); File archivo = new File("Reporte de Compras.xls"); Cell celda; String[] titulos = { "Nomina", "Compras", "Gastos Fijos", "Gastos Variables", "Gastos Otros" }; Double[] datos = { d_comp_nom, d_comp_comp, d_comp_gf, d_comp_gv, d_comp_go }; int i; for (i = 0; i < titulos.length; i++) { celda = fila.createCell(i); celda.setCellValue(titulos[i]); } fila = sheet.createRow(1); for (i = 0; i < datos.length; i++) { celda = fila.createCell(i); celda.setCellValue(datos[i]); } try { FileOutputStream out = new FileOutputStream(archivo); workbook.write(out); out.close(); System.out.println("Archivo creado exitosamente!"); } catch (IOException ex) { System.out.println("Error de escritura"); ex.printStackTrace(); } } }); archivo.add(guardar); menu.add(archivo); frame_grafica.getContentPane().add(panel_grafica); frame_grafica.setBounds(60, 60, 450, 400); frame_grafica.setJMenuBar(menu); frame_grafica.setVisible(true); frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } if (combobox.getSelectedIndex() == 2) { datos_ventas.addValue(d_vent_s1_lu, "Semana 1", "Lunes"); datos_ventas.addValue(d_vent_s1_ma, "Semana 1", "Martes"); datos_ventas.addValue(d_vent_s1_mi, "Semana 1", "Mircoles"); datos_ventas.addValue(d_vent_s1_ju, "Semana 1", "Jueves"); datos_ventas.addValue(d_vent_s1_vi, "Semana 1", "Viernes"); datos_ventas.addValue(d_vent_s1_sa, "Semana 1", "Sbado"); datos_ventas.addValue(d_vent_s1_do, "Semana 1", "Domingo"); datos_ventas.addValue(d_vent_s2_lu, "Semana 2", "Lunes"); datos_ventas.addValue(d_vent_s2_ma, "Semana 2", "Martes"); datos_ventas.addValue(d_vent_s2_mi, "Semana 2", "Mircoles"); datos_ventas.addValue(d_vent_s2_ju, "Semana 2", "Jueves"); datos_ventas.addValue(d_vent_s2_vi, "Semana 2", "Viernes"); datos_ventas.addValue(d_vent_s2_sa, "Semana 2", "Sbado"); datos_ventas.addValue(d_vent_s2_do, "Semana 2", "Domingo"); Grafica = ChartFactory.createLineChart3D("Ventas", "Das", "Ingresos", datos_ventas, PlotOrientation.VERTICAL, true, true, false); ChartPanel panel_grafica = new ChartPanel(Grafica); JFrame frame_grafica = new JFrame("Grfico"); JMenuBar menu = new JMenuBar(); JMenu archivo = new JMenu("Archivo"); JMenuItem guardar = new JMenuItem("Guardar como reporte..."); guardar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Document document = new Document(); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, new FileOutputStream("Grfico Ventas.pdf")); } catch (DocumentException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(450, 450); Graphics2D g2 = tp.createGraphicsShapes(450, 450); menu.setVisible(false); frame_grafica.print(g2); menu.setVisible(true); g2.dispose(); cb.addTemplate(tp, 30, 400); document.close(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Reporte de Ventas"); Row fila = sheet.createRow(0); File archivo = new File("Reporte de Ventas.xls"); Cell celda; String[] titulos1 = { "S1 lunes", "S1 martes", "S1 miercoles", "S1 jueves", "S1 viernes", "S1 sabado", "S1 domingo" }; String[] titulos2 = { "S2 lunes", "S2 martes", "S2 miercoles", "S2 jueves", "S2 viernes", "S2 sabado", "S2 domingo" }; Double[] datos1 = { d_vent_s1_lu, d_vent_s1_ma, d_vent_s1_mi, d_vent_s1_ju, d_vent_s1_vi, d_vent_s1_sa, d_vent_s1_do }; Double[] datos2 = { d_vent_s2_lu, d_vent_s2_ma, d_vent_s2_mi, d_vent_s2_ju, d_vent_s2_vi, d_vent_s2_sa, d_vent_s2_do }; int i, j; for (i = 0; i < titulos1.length; i++) { celda = fila.createCell(i); celda.setCellValue(titulos1[i]); } fila = sheet.createRow(1); for (i = 0; i < datos1.length; i++) { celda = fila.createCell(i); celda.setCellValue(datos1[i]); } fila = sheet.createRow(3); for (j = 0; j < titulos2.length; j++) { celda = fila.createCell(j); celda.setCellValue(titulos2[j]); } fila = sheet.createRow(4); for (j = 0; j < datos2.length; j++) { celda = fila.createCell(j); celda.setCellValue(datos2[j]); } try { FileOutputStream out = new FileOutputStream(archivo); workbook.write(out); out.close(); System.out.println("Archivo creado exitosamente!"); } catch (IOException ex) { System.out.println("Error de escritura"); ex.printStackTrace(); } } }); archivo.add(guardar); menu.add(archivo); frame_grafica.getContentPane().add(panel_grafica); frame_grafica.setBounds(60, 60, 450, 400); frame_grafica.setJMenuBar(menu); frame_grafica.setVisible(true); frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } if (combobox.getSelectedIndex() == 3) { datos_inventario.setValue("Producto 1", d_inv_p1); datos_inventario.setValue("Producto 2", d_inv_p2); datos_inventario.setValue("Producto 3", d_inv_p3); datos_inventario.setValue("Producto 4", d_inv_p4); datos_inventario.setValue("Producto 5", d_inv_p5); Grafica = ChartFactory.createPieChart3D("Inventario", datos_inventario, true, true, true); ChartPanel panel_grafica = new ChartPanel(Grafica); JFrame frame_grafica = new JFrame("Grfico"); JMenuBar menu = new JMenuBar(); JMenu archivo = new JMenu("Archivo"); JMenuItem guardar = new JMenuItem("Guardar como reporte..."); guardar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Document document = new Document(); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, new FileOutputStream("Grfico Inventario.pdf")); } catch (DocumentException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(450, 450); Graphics2D g2 = tp.createGraphicsShapes(450, 450); menu.setVisible(false); frame_grafica.print(g2); menu.setVisible(true); g2.dispose(); cb.addTemplate(tp, 30, 400); document.close(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Reporte de Inventario"); Row fila = sheet.createRow(0); File archivo = new File("Reporte de Inventario.xls"); Cell celda; String[] titulos = { "Producto 1", "Producto 2", "Prroducto 3", "Producto 4", "Producto 5" }; Double[] datos = { d_inv_p1, d_inv_p2, d_inv_p3, d_inv_p4, d_inv_p5 }; int i; for (i = 0; i < titulos.length; i++) { celda = fila.createCell(i); celda.setCellValue(titulos[i]); } fila = sheet.createRow(1); for (i = 0; i < datos.length; i++) { celda = fila.createCell(i); celda.setCellValue(datos[i]); } try { FileOutputStream out = new FileOutputStream(archivo); workbook.write(out); out.close(); System.out.println("Archivo creado exitosamente!"); } catch (IOException ex) { System.out.println("Error de escritura"); ex.printStackTrace(); } } }); archivo.add(guardar); menu.add(archivo); frame_grafica.getContentPane().add(panel_grafica); frame_grafica.setBounds(60, 60, 450, 400); frame_grafica.setJMenuBar(menu); frame_grafica.setVisible(true); frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } if (combobox.getSelectedIndex() == 4) { datos_contabilidad.addValue(d_cont_e_lu, "Entradas", "Lunes"); datos_contabilidad.addValue(d_cont_e_ma, "Entradas", "Martes"); datos_contabilidad.addValue(d_cont_e_mi, "Entradas", "Mircoles"); datos_contabilidad.addValue(d_cont_e_ju, "Entradas", "Jueves"); datos_contabilidad.addValue(d_cont_e_vi, "Entradas", "Viernes"); datos_contabilidad.addValue(d_cont_e_sa, "Entradas", "Sbado"); datos_contabilidad.addValue(d_cont_e_do, "Entradas", "Domingo"); datos_contabilidad.addValue(d_cont_s_lu, "Salidas", "Lunes"); datos_contabilidad.addValue(d_cont_s_ma, "Salidas", "Martes"); datos_contabilidad.addValue(d_cont_s_mi, "Salidas", "Mircoles"); datos_contabilidad.addValue(d_cont_s_ju, "Salidas", "Jueves"); datos_contabilidad.addValue(d_cont_s_vi, "Salidas", "Viernes"); datos_contabilidad.addValue(d_cont_s_sa, "Salidas", "Sbado"); datos_contabilidad.addValue(d_cont_s_do, "Salidas", "Domingo"); datos_contabilidad.addValue(d_cont_u_lu, "Utilidades", "Lunes"); datos_contabilidad.addValue(d_cont_u_ma, "Utilidades", "Martes"); datos_contabilidad.addValue(d_cont_u_mi, "Utilidades", "Mircoles"); datos_contabilidad.addValue(d_cont_u_ju, "Utilidades", "Jueves"); datos_contabilidad.addValue(d_cont_u_vi, "Utilidades", "Viernes"); datos_contabilidad.addValue(d_cont_u_sa, "Utilidades", "Sbado"); datos_contabilidad.addValue(d_cont_u_do, "Utilidades", "Domingo"); Grafica = ChartFactory.createLineChart3D("Contabilidad", "Das", "Ingresos", datos_contabilidad, PlotOrientation.VERTICAL, true, true, false); ChartPanel panel_grafica = new ChartPanel(Grafica); JFrame frame_grafica = new JFrame("Grfico"); JMenuBar menu = new JMenuBar(); JMenu archivo = new JMenu("Archivo"); JMenuItem guardar = new JMenuItem("Guardar como reporte..."); guardar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Document document = new Document(); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, new FileOutputStream("Grfico Contabilidad.pdf")); } catch (DocumentException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(450, 450); Graphics2D g2 = tp.createGraphicsShapes(450, 450); menu.setVisible(false); frame_grafica.print(g2); menu.setVisible(true); g2.dispose(); cb.addTemplate(tp, 30, 400); document.close(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Reporte de Contabilidad"); Row fila = sheet.createRow(0); File archivo = new File("Reporte de Contabilidad.xls"); Cell celda; String[] t_ent = { "E lunes", "E martes", "E miercoles", "E jueves", "E viernes", "E sabado", "E domingo" }; String[] t_sal = { "S lunes", "S martes", "S miercoles", "S jueves", "S viernes", "S sabado", "S domingo" }; String[] t_uti = { "U lunes", "U martes", "U miercoles", "U jueves", "U viernes", "U sabado", "U domingo" }; Double[] d_ent = { d_cont_e_lu, d_cont_e_ma, d_cont_e_mi, d_cont_e_ju, d_cont_e_vi, d_cont_e_sa, d_cont_e_do }; Double[] d_sal = { d_cont_s_lu, d_cont_s_ma, d_cont_s_mi, d_cont_s_ju, d_cont_s_vi, d_cont_s_sa, d_cont_s_do }; Double[] d_uti = { d_cont_u_lu, d_cont_u_ma, d_cont_u_mi, d_cont_u_ju, d_cont_u_vi, d_cont_u_sa, d_cont_u_do }; int i, j, k; for (i = 0; i < t_ent.length; i++) { celda = fila.createCell(i); celda.setCellValue(t_ent[i]); } fila = sheet.createRow(1); for (i = 0; i < d_ent.length; i++) { celda = fila.createCell(i); celda.setCellValue(d_ent[i]); } fila = sheet.createRow(3); for (j = 0; j < t_sal.length; j++) { celda = fila.createCell(j); celda.setCellValue(t_sal[j]); } fila = sheet.createRow(4); for (j = 0; j < d_sal.length; j++) { celda = fila.createCell(j); celda.setCellValue(d_sal[j]); } fila = sheet.createRow(6); for (k = 0; k < t_uti.length; k++) { celda = fila.createCell(k); celda.setCellValue(t_uti[k]); } fila = sheet.createRow(7); for (k = 0; k < d_uti.length; k++) { celda = fila.createCell(k); celda.setCellValue(d_uti[k]); } try { FileOutputStream out = new FileOutputStream(archivo); workbook.write(out); out.close(); System.out.println("Archivo creado exitosamente!"); } catch (IOException ex) { System.out.println("Error de escritura"); ex.printStackTrace(); } } }); archivo.add(guardar); menu.add(archivo); frame_grafica.getContentPane().add(panel_grafica); frame_grafica.setBounds(60, 60, 450, 400); frame_grafica.setJMenuBar(menu); frame_grafica.setVisible(true); frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } if (combobox.getSelectedIndex() == 5) { datos_rec_hum.addValue(d_rh_a_lu, "Asistencias", "Lunes"); datos_rec_hum.addValue(d_rh_a_ma, "Asistencias", "Martes"); datos_rec_hum.addValue(d_rh_a_mi, "Asistencias", "Mircoles"); datos_rec_hum.addValue(d_rh_a_ju, "Asistencias", "Jueves"); datos_rec_hum.addValue(d_rh_a_vi, "Asistencias", "Viernes"); datos_rec_hum.addValue(d_rh_a_sa, "Asistencias", "Sbado"); datos_rec_hum.addValue(d_rh_a_do, "Asistencias", "Domingo"); datos_rec_hum.addValue(d_rh_r_lu, "Retardos", "Lunes"); datos_rec_hum.addValue(d_rh_r_ma, "Retardos", "Martes"); datos_rec_hum.addValue(d_rh_r_mi, "Retardos", "Mircoles"); datos_rec_hum.addValue(d_rh_r_ju, "Retardos", "Jueves"); datos_rec_hum.addValue(d_rh_r_vi, "Retardos", "Viernes"); datos_rec_hum.addValue(d_rh_r_sa, "Retardos", "Sbado"); datos_rec_hum.addValue(d_rh_r_do, "Retardos", "Domingo"); datos_rec_hum.addValue(d_rh_f_lu, "Faltas", "Lunes"); datos_rec_hum.addValue(d_rh_f_ma, "Faltas", "Martes"); datos_rec_hum.addValue(d_rh_f_mi, "Faltas", "Mircoles"); datos_rec_hum.addValue(d_rh_f_ju, "Faltas", "Jueves"); datos_rec_hum.addValue(d_rh_f_vi, "Faltas", "Viernes"); datos_rec_hum.addValue(d_rh_f_sa, "Faltas", "Sbado"); datos_rec_hum.addValue(d_rh_f_do, "Faltas", "Domingo"); Grafica = ChartFactory.createBarChart3D("Recursos Humanos", "Das", "Nmero de Empleados", datos_rec_hum, PlotOrientation.VERTICAL, true, true, false); ChartPanel panel_grafica = new ChartPanel(Grafica); JFrame frame_grafica = new JFrame("Grfico"); JMenuBar menu = new JMenuBar(); JMenu archivo = new JMenu("Archivo"); JMenuItem guardar = new JMenuItem("Guardar como reporte..."); guardar.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Document document = new Document(); PdfWriter writer = null; try { writer = PdfWriter.getInstance(document, new FileOutputStream("Grfico Recursos Humanos.pdf")); } catch (DocumentException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } catch (FileNotFoundException ex) { Logger.getLogger(JFrame.class.getName()).log(Level.SEVERE, null, ex); } document.open(); PdfContentByte cb = writer.getDirectContent(); PdfTemplate tp = cb.createTemplate(450, 450); Graphics2D g2 = tp.createGraphicsShapes(450, 450); menu.setVisible(false); frame_grafica.print(g2); menu.setVisible(true); g2.dispose(); cb.addTemplate(tp, 30, 400); document.close(); HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = workbook.createSheet("Reporte de Recursos Humanos"); Row fila = sheet.createRow(0); File archivo = new File("Reporte de Recursos Humanos.xls"); Cell celda; String[] t_asi = { "A lunes", "A martes", "A miercoles", "A jueves", "A viernes", "A sabado", "A domingo" }; String[] t_ret = { "R lunes", "R martes", "R miercoles", "R jueves", "R viernes", "R sabado", "R domingo" }; String[] t_fal = { "F lunes", "F martes", "F miercoles", "F jueves", "F viernes", "F sabado", "F domingo" }; int[] d_asi = { d_rh_a_lu, d_rh_a_ma, d_rh_a_mi, d_rh_a_ju, d_rh_a_vi, d_rh_a_sa, d_rh_a_do }; int[] d_ret = { d_rh_r_lu, d_rh_r_ma, d_rh_r_mi, d_rh_r_ju, d_rh_r_vi, d_rh_r_sa, d_rh_r_do }; int[] d_fal = { d_rh_f_lu, d_rh_r_ma, d_rh_r_mi, d_rh_r_ju, d_rh_r_vi, d_rh_r_sa, d_rh_r_do }; int i, j, k; for (i = 0; i < t_asi.length; i++) { celda = fila.createCell(i); celda.setCellValue(t_asi[i]); } fila = sheet.createRow(1); for (i = 0; i < d_asi.length; i++) { celda = fila.createCell(i); celda.setCellValue(d_asi[i]); } fila = sheet.createRow(3); for (j = 0; j < t_ret.length; j++) { celda = fila.createCell(j); celda.setCellValue(t_ret[j]); } fila = sheet.createRow(4); for (j = 0; j < d_ret.length; j++) { celda = fila.createCell(j); celda.setCellValue(d_ret[j]); } fila = sheet.createRow(6); for (k = 0; k < t_fal.length; k++) { celda = fila.createCell(k); celda.setCellValue(t_fal[k]); } fila = sheet.createRow(7); for (k = 0; k < d_fal.length; k++) { celda = fila.createCell(k); celda.setCellValue(d_fal[k]); } try { FileOutputStream out = new FileOutputStream(archivo); workbook.write(out); out.close(); System.out.println("Archivo creado exitosamente!"); } catch (IOException ex) { System.out.println("Error de escritura"); ex.printStackTrace(); } } }); archivo.add(guardar); menu.add(archivo); frame_grafica.getContentPane().add(panel_grafica); frame_grafica.setBounds(60, 60, 450, 400); frame_grafica.setJMenuBar(menu); frame_grafica.setVisible(true); frame_grafica.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } } }); jPanel = new JPanel(); jPanel.setLayout(null); jPanel.add(cal1); jPanel.add(cal2); jPanel.add(etiqueta); jPanel.add(combobox); jPanel.add(calendario); jPanel.add(aceptar); jFrame.setJMenuBar(jMenuBar); jFrame.add(jPanel); jFrame.setVisible(true); }
From source file:psidev.psi.mi.tab.client.gui.DragAndDropConverter.java
/** * Drag and Drop MITAB25 Converter.//from w w w. j ava2s. co m */ public static void main(String[] args) throws FileNotFoundException { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { log.error("Failed to change Look and Feel.", e); } // Create and set up the window. final JFrame frame = new javax.swing.JFrame("MITAB25 Converter"); frame.setPreferredSize(new Dimension(400, 200)); JPanel panel = new JPanel(); panel.setLayout(new GridBagLayout()); frame.add(panel); addMenuBar(frame); Component label = new JLabel("Drag and drop your XML file(s) here"); label.setPreferredSize(new Dimension(400, 200)); label.setForeground(Color.red); panel.add(label); // Handle the dropped files PrintStream out = null; // could be System.out new DragAndDropComponent(out, panel, new FilesDroppedListener() { public void filesDropped(java.io.File[] files) { FilesProcessor processor = new FilesProcessor(); processor.process(frame, files, expansionStrategy, postProcessorStrategy, aggregateSelectedFiles); } }); // end FileDrop.Listener // Set up the window. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(100, 100, 50, 50); // the size of the frame is defined by its internal component. frame.pack(); frame.setVisible(true); }
From source file:psidev.psi.mi.validator.client.gui.DragAndDropValidator.java
/** * Runs a sample program that shows dropped files */// w w w .ja v a2 s . com public static void main(String[] args) throws FileNotFoundException, ValidatorException { // TODO ValidatorException should popup instead of appearing in the background (ie. console) if (args.length == 0 || args.length > 2) { System.err.println("Usage: DragAndDropValidator <validator_config_file> [log level]"); System.exit(1); } // setup Logging. Log4jConfigurator.configure(); String configFile = args[0]; final MessageLevel level; if (args.length == 2) { level = MessageLevel.forName(args[1]); log.info("User requested log level: " + level); } else { level = MessageLevel.WARN; // default log.info("Message Level set to default: " + level); } FileInputStream configStream = new FileInputStream(configFile); Validator validator = null; try { validator = new MiValidator(configStream, null, null); } catch (OntologyLoaderException e) { throw new ValidatorException("", e); } finally { try { configStream.close(); } catch (IOException e) { e.printStackTrace(); } } //Create and set up the window. final JFrame frame = new javax.swing.JFrame("PSI-MI 2.5 Drag & Drop Validator"); //Create and set up the content pane. final ValidatorTable validatorTable = new ValidatorTable(validator); validatorTable.setOpaque(true); //content panes must be opaque frame.setContentPane(validatorTable); // Handle the dropped files PrintStream out = null; // could be System.out new DragAndDropComponent(out, validatorTable, new FilesDroppedListener() { public void filesDropped(java.io.File[] files) { for (int i = 0; i < files.length; i++) { ValidatorTableRow row = new ValidatorTableRow(files[i], level, true); validatorTable.addTableRow(row); } // end for: through each dropped file } // end filesDropped }); // end FileDrop.Listener // Set up menus setupMenus(frame, validator, validatorTable, level); // Set up the window. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setBounds(100, 100, 50, 50); // the size of the frame is defined by its internal component. frame.pack(); frame.setVisible(true); }