Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

1190
LINES

< > BotCompany Repo | #1016163 // Tabbed JxBrowser [Include]

JavaX fragment (include)

lib 1400047 lib 1400102 // jxbrowser icons & license
static L<S> _stickyLibs_1016163 = ll(#1400047, #1400102);

import com.teamdev.jxbrowser.chromium.demo.resources.Resources;
import com.teamdev.jxbrowser.chromium.events.Callback;
import com.teamdev.jxbrowser.chromium.*;
import com.teamdev.jxbrowser.chromium.events.*;
import com.teamdev.jxbrowser.chromium.internal.Environment;
import com.teamdev.jxbrowser.chromium.swing.*;

import java.beans.*;

sclass TabbedPane extends JPanel {
  private final List<Tab> tabs;
  private final TabCaptions captions;
  private final JComponent contentContainer;
  bool hasNewTabButton;
  BrowserContext context;

  *(BrowserContext *context) {
      this.captions = new TabCaptions();
      this.tabs = new ArrayList<Tab>();
      this.contentContainer = new JPanel(new BorderLayout());

      setLayout(new BorderLayout());
      add(captions, BorderLayout.NORTH);
      add(contentContainer, BorderLayout.CENTER);
      
      insertNewTabButton();
  }
  
  void insertNewTabButton() {
    if (hasNewTabButton) ret;
    hasNewTabButton = true;
    TabButton button = new TabButton(Resources.getIcon("new-tab.png"), "New tab");
    button.addActionListener(actionListener {
      addAndSelectTab(TabFactory.createTab(context));
    });
    addTabButton(button);
  }

  public void disposeAllTabs() {
      for (Tab tab : getTabs()) {
          disposeTab(tab);
      }
  }

  private void disposeTab(Tab tab) {
      tab.getCaption().setSelected(false);
      tab.getContent().dispose();
      removeTab(tab);
      if (hasTabs()) {
          Tab firstTab = getFirstTab();
          firstTab.getCaption().setSelected(true);
      } else
          disposeInternalFrame(this);
  }

  private Tab findTab(TabCaption item) {
      for (Tab tab : getTabs()) {
          if (tab.getCaption().equals(item)) {
              return tab;
          }
      }
      return null;
  }


  void addAndSelectTab(Tab tab) {
    addTab(tab);
    selectTab(tab);
  }

  public void addTab(final Tab tab) {
      TabCaption caption = tab.getCaption();
      caption.addPropertyChangeListener("CloseButtonPressed", new TabCaptionCloseTabListener());
      caption.addPropertyChangeListener("TabSelected", new SelectTabListener());

      TabContent content = tab.getContent();
      content.addPropertyChangeListener("TabClosed", new TabContentCloseTabListener());

      captions.addTab(caption);
      tabs.add(tab);
      validate();
      repaint();
  }

  private boolean hasTabs() {
      return !tabs.isEmpty();
  }

  private Tab getFirstTab() {
      return tabs.get(0);
  }

  private List<Tab> getTabs() {
      return new ArrayList<Tab>(tabs);
  }

  public void removeTab(Tab tab) {
      TabCaption tabCaption = tab.getCaption();
      captions.removeTab(tabCaption);
      tabs.remove(tab);
      validate();
      repaint();
  }

  public void addTabButton(TabButton button) {
      captions.addTabButton(button);
  }

  public void selectTab(Tab tab) {
      TabCaption tabCaption = tab.getCaption();
      TabCaption selectedTab = captions.getSelectedTab();
      if (selectedTab != null && !selectedTab.equals(tabCaption)) {
          selectedTab.setSelected(false);
      }
      captions.setSelectedTab(tabCaption);
  }

  private class TabCaptionCloseTabListener implements PropertyChangeListener {
      public void propertyChange(PropertyChangeEvent evt) {
          TabCaption caption = (TabCaption) evt.getSource();
          Tab tab = findTab(caption);
          disposeTab(tab);
      }
  }

  private class SelectTabListener implements PropertyChangeListener {
      public void propertyChange(PropertyChangeEvent evt) {
          TabCaption caption = (TabCaption) evt.getSource();
          Tab tab = findTab(caption);
          if (caption.isSelected()) {
              selectTab(tab);
          }
          if (!caption.isSelected()) {
              TabContent content = tab.getContent();
              contentContainer.remove(content);
              contentContainer.validate();
              contentContainer.repaint();
          } else {
              final TabContent content = tab.getContent();
              contentContainer.add(content, BorderLayout.CENTER);
              contentContainer.validate();
              contentContainer.repaint();
          }
      }
  }

  private class TabContentCloseTabListener implements PropertyChangeListener {
      public void propertyChange(PropertyChangeEvent evt) {
          TabContent content = (TabContent) evt.getSource();
          Tab tab = findTab(content);
          disposeTab(tab);
      }

      private Tab findTab(TabContent content) {
          for (Tab tab : getTabs()) {
              if (tab.getContent().equals(content)) {
                  return tab;
              }
          }
          return null;
      }
  }
}

static class TabFactory {

  public static Tab createTab(BrowserContext context) {
      return createTab(context, "about:blank");
  }

  public static Tab createTab(BrowserContext context, String url) {
    Browser browser = new Browser(BrowserType.LIGHTWEIGHT, context);
    print("Made browser " + browser);
    BrowserView browserView = new BrowserView(browser);
      TabContent tabContent = new TabContent(browserView);

      browser.setDownloadHandler(new DefaultDownloadHandler(browserView));
      browser.setDialogHandler(new DefaultDialogHandler(browserView));
      browser.setPopupHandler(new DefaultPopupHandler());

      final TabCaption tabCaption = new TabCaption();
      tabCaption.setTitle("about:blank");

      tabContent.addPropertyChangeListener("PageTitleChanged", new PropertyChangeListener() {
          public void propertyChange(PropertyChangeEvent evt) {
              tabCaption.setTitle((String) evt.getNewValue());
          }
      });

      browser.loadURL(url);
      return new Tab(tabCaption, tabContent);
  }
}

sclass Tab {

    private final TabCaption caption;
    private final TabContent content;

    public Tab(TabCaption caption, TabContent content) {
        this.caption = caption;
        this.content = content;
    }

    public TabCaption getCaption() {
        return caption;
    }

    public TabContent getContent() {
        return content;
    }
}

sclass TabButton extends JButton {

    public TabButton(Icon icon, String toolTipText) {
        setIcon(icon);
        setToolTipText(toolTipText);
        setOpaque(false);
        setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
        setContentAreaFilled(false);
        setFocusable(false);
    }

}

sclass TabCaption extends JPanel {

    private boolean selected;
    private TabCaptionComponent component;

    public TabCaption() {
        setLayout(new BorderLayout());
        setOpaque(false);
        add(createComponent(), BorderLayout.CENTER);
        add(Box.createHorizontalStrut(1), BorderLayout.EAST);
    }

    private JComponent createComponent() {
        component = new TabCaptionComponent();
        component.addPropertyChangeListener("CloseButtonPressed", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                firePropertyChange("CloseButtonPressed", evt.getOldValue(), evt.getNewValue());
            }
        });
        component.addPropertyChangeListener("TabClicked", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                setSelected(true);
            }
        });
        return component;
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(155, 26);
    }

    @Override
    public Dimension getMinimumSize() {
        return new Dimension(50, 26);
    }

    @Override
    public Dimension getMaximumSize() {
        return getPreferredSize();
    }

    public void setTitle(String title) {
        component.setTitle(title);
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        boolean oldValue = this.selected;
        this.selected = selected;
        component.setSelected(selected);
        firePropertyChange("TabSelected", oldValue, selected);
    }

    private static class TabCaptionComponent extends JPanel {

        private final Color defaultBackground;
        private JLabel label;

        private TabCaptionComponent() {
            defaultBackground = getBackground();
            setLayout(new BorderLayout());
            setOpaque(false);
            add(createLabel(), BorderLayout.CENTER);
            add(createCloseButton(), BorderLayout.EAST);
        }

        private JComponent createLabel() {
            label = new JLabel();
            label.setOpaque(false);
            label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
            label.addMouseListener(new MouseAdapter() {
                @Override
                public void mousePressed(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        firePropertyChange("TabClicked", false, true);
                    }
                    if (e.getButton() == MouseEvent.BUTTON2) {
                        firePropertyChange("CloseButtonPressed", false, true);
                    }
                }
            });
            return label;
        }

        private JComponent createCloseButton() {
            JButton closeButton = new JButton();
            closeButton.setOpaque(false);
            closeButton.setToolTipText("Close");
            closeButton.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
            closeButton.setPressedIcon(Resources.getIcon("close-pressed.png"));
            closeButton.setIcon(Resources.getIcon("close.png"));
            closeButton.setContentAreaFilled(false);
            closeButton.setFocusable(false);
            closeButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    firePropertyChange("CloseButtonPressed", false, true);
                }
            });
            return closeButton;
        }

        public void setTitle(final String title) {
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    label.setText(title);
                    label.setToolTipText(title);
                }
            });
        }

        public void setSelected(boolean selected) {
            setBackground(selected ? defaultBackground : new Color(150, 150, 150));
            repaint();
        }

        @Override
        public void paint(Graphics g) {
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            g2d.setPaint(
                    new GradientPaint(0, 0, Color.LIGHT_GRAY, 0, getHeight(), getBackground()));
            g2d.fillRect(0, 0, getWidth(), getHeight());
            g2d.dispose();
            super.paint(g);
        }
    }
}

sclass TabCaptions extends JPanel {

    private TabCaption selectedTab;

    private JPanel tabsPane;
    private JPanel buttonsPane;

    public TabCaptions() {
        createUI();
    }

    private void createUI() {
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
        setBackground(Color.DARK_GRAY);
        add(createItemsPane());
        add(createButtonsPane());
        add(Box.createHorizontalGlue());
    }

    private JComponent createItemsPane() {
        tabsPane = new JPanel();
        tabsPane.setOpaque(false);
        tabsPane.setLayout(new BoxLayout(tabsPane, BoxLayout.X_AXIS));
        return tabsPane;
    }

    private JComponent createButtonsPane() {
        buttonsPane = new JPanel();
        buttonsPane.setOpaque(false);
        buttonsPane.setLayout(new BoxLayout(buttonsPane, BoxLayout.X_AXIS));
        return buttonsPane;
    }

    public void addTab(TabCaption item) {
        tabsPane.add(item);
    }

    public void removeTab(TabCaption item) {
        tabsPane.remove(item);
    }

    public void addTabButton(TabButton button) {
        buttonsPane.add(button);
    }

    public TabCaption getSelectedTab() {
        return selectedTab;
    }

    public void setSelectedTab(TabCaption selectedTab) {
        this.selectedTab = selectedTab;
        this.selectedTab.setSelected(true);
    }
}

sclass TabContent extends JPanel {

    private final BrowserView browserView;
    private final ToolBar toolBar;
    private final JComponent jsConsole;
    private final JComponent container;
    private final JComponent browserContainer;

    public TabContent(final BrowserView browserView) {
        this.browserView = browserView;
        this.browserView.getBrowser().addLoadListener(new LoadAdapter() {
            @Override
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    firePropertyChange("PageTitleChanged", null,
                            TabContent.this.browserView.getBrowser().getTitle());
                }
            }
        });

        this.browserView.getBrowser().addTitleListener(new TitleListener() {
            @Override
            public void onTitleChange(TitleEvent event) {
                firePropertyChange("PageTitleChanged", null, event.getTitle());
            }
        });

        browserContainer = createBrowserContainer();
        jsConsole = createConsole();
        toolBar = createToolBar(browserView);

        container = new JPanel(new BorderLayout());
        container.add(browserContainer, BorderLayout.CENTER);

        setLayout(new BorderLayout());
        add(toolBar, BorderLayout.NORTH);
        add(container, BorderLayout.CENTER);
    }

    private ToolBar createToolBar(BrowserView browserView) {
        ToolBar toolBar = new ToolBar(browserView);
        toolBar.addPropertyChangeListener("TabClosed", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                firePropertyChange("TabClosed", false, true);
            }
        });
        toolBar.addPropertyChangeListener("JSConsoleDisplayed", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                showConsole();
            }
        });
        toolBar.addPropertyChangeListener("JSConsoleClosed", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                hideConsole();
            }
        });
        return toolBar;
    }

    private void hideConsole() {
        showComponent(browserContainer);
    }

    private void showComponent(JComponent component) {
        container.removeAll();
        container.add(component, BorderLayout.CENTER);
        validate();
    }

    private void showConsole() {
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
        splitPane.add(browserContainer, JSplitPane.TOP);
        splitPane.add(jsConsole, JSplitPane.BOTTOM);
        splitPane.setResizeWeight(0.8);
        splitPane.setBorder(BorderFactory.createEmptyBorder());
        showComponent(splitPane);
    }

    private JComponent createConsole() {
        JSConsole result = new JSConsole(browserView.getBrowser());
        result.addPropertyChangeListener("JSConsoleClosed", new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
                hideConsole();
                toolBar.didJSConsoleClose();
            }
        });
        return result;
    }

    private JComponent createBrowserContainer() {
        JPanel container = new JPanel(new BorderLayout());
        container.add(browserView, BorderLayout.CENTER);
        return container;
    }

    public void dispose() {
      Browser b = browserView.getBrowser();
      _print("Disposing browser " + b);
      b.dispose();
    }
}

sclass ToolBar extends JPanel {
    private static final String RUN_JAVASCRIPT = "Run JavaScript...";
    private static final String CLOSE_JAVASCRIPT = "Close JavaScript Console";
    private static final String DEFAULT_URL = "about:blank";
    private final JTextField addressBar;
    private final BrowserView browserView;
    private JButton backwardButton;
    private JButton forwardButton;
    private JButton refreshButton;
    private JButton stopButton;
    private JMenuItem consoleMenuItem;

    public ToolBar(BrowserView browserView) {
        this.browserView = browserView;
        addressBar = createAddressBar();
        setLayout(new GridBagLayout());
        add(createActionsPane(),
                new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
                        GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
        add(addressBar, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0,
                GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(4, 0, 4, 5), 0, 0));
        add(createMenuButton(), new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
                GridBagConstraints.LINE_END, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 5),
                0, 0));
    }

    private static JButton createBackwardButton(final Browser browser) {
        return createButton("Back", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                browser.goBack();
            }
        });
    }

    private static JButton createForwardButton(final Browser browser) {
        return createButton("Forward", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                browser.goForward();
            }
        });
    }

    private static JButton createRefreshButton(final Browser browser) {
        return createButton("Refresh", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                browser.reload();
            }
        });
    }

    private static JButton createStopButton(final Browser browser) {
        return createButton("Stop", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                browser.stop();
            }
        });
    }

    private static JButton createButton(String caption, Action action) {
        ActionButton button = new ActionButton(caption, action);
        String imageName = caption.toLowerCase();
        button.setIcon(Resources.getIcon(imageName + ".png"));
        button.setRolloverIcon(Resources.getIcon(imageName + "-selected.png"));
        return button;
    }

    private static JCheckBoxMenuItem createCheckBoxMenuItem(String title, boolean selected,
            final CheckBoxMenuItemCallback action) {
        final JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(title, selected);
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                action.call(menuItem.isSelected());
            }
        });
        return menuItem;
    }

    public void didJSConsoleClose() {
        consoleMenuItem.setText(RUN_JAVASCRIPT);
    }

    private JPanel createActionsPane() {
        backwardButton = createBackwardButton(browserView.getBrowser());
        forwardButton = createForwardButton(browserView.getBrowser());
        refreshButton = createRefreshButton(browserView.getBrowser());
        stopButton = createStopButton(browserView.getBrowser());

        JPanel actionsPanel = new JPanel();
        actionsPanel.add(backwardButton);
        actionsPanel.add(forwardButton);
        actionsPanel.add(refreshButton);
        actionsPanel.add(stopButton);
        return actionsPanel;
    }

    private JTextField createAddressBar() {
        final JTextField result = new JTextField(DEFAULT_URL);
        result.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().loadURL(result.getText());
            }
        });

        browserView.getBrowser().addLoadListener(new LoadAdapter() {
            @Override
            public void onStartLoadingFrame(StartLoadingEvent event) {
                if (event.isMainFrame()) {
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            refreshButton.setEnabled(false);
                            stopButton.setEnabled(true);
                        }
                    });
                }
            }

            @Override
            public void onProvisionalLoadingFrame(final ProvisionalLoadingEvent event) {
                if (event.isMainFrame()) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override
                        public void run() {
                            result.setText(event.getURL());
                            result.setCaretPosition(result.getText().length());

                            Browser browser = event.getBrowser();
                            forwardButton.setEnabled(browser.canGoForward());
                            backwardButton.setEnabled(browser.canGoBack());
                        }
                    });
                }
            }

            @Override
            public void onFinishLoadingFrame(final FinishLoadingEvent event) {
                if (event.isMainFrame()) {
                    SwingUtilities.invokeLater(new Runnable() {
                        public void run() {
                            refreshButton.setEnabled(true);
                            stopButton.setEnabled(false);
                        }
                    });
                }
            }
        });
        return result;
    }

    private JComponent createMenuButton() {
        final JPopupMenu popupMenu = new JPopupMenu();
        popupMenu.add(createConsoleMenuItem());
        popupMenu.add(createGetHTMLMenuItem());
        popupMenu.add(createPopupsMenuItem());
        popupMenu.add(createUploadFileMenuItem());
        popupMenu.add(createDownloadFileMenuItem());
        popupMenu.add(createJavaScriptDialogsMenuItem());
        popupMenu.add(createPDFViewerMenuItem());
        popupMenu.add(createFlashMenuItem());
        popupMenu.add(createGoogleMapsMenuItem());
        popupMenu.add(createHTML5VideoMenuItem());
        popupMenu.add(createZoomInMenuItem());
        popupMenu.add(createZoomOutMenuItem());
        popupMenu.add(createActualSizeMenuItem());
        popupMenu.add(createSaveWebPageMenuItem());
        popupMenu.add(createClearCacheMenuItem());
        popupMenu.add(createPreferencesSubMenu());
        popupMenu.add(createExecuteCommandSubMenu());
        popupMenu.add(createPrintMenuItem());
        popupMenu.addSeparator();
        popupMenu.add(createMoreMenuItem());
        popupMenu.addSeparator();
        //popupMenu.add(createAboutMenuItem());

        final ActionButton button = new ActionButton("Preferences", null);
        button.setIcon(Resources.getIcon("gear.png"));
        button.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                    popupMenu.show(e.getComponent(), 0, button.getHeight());
                } else {
                    popupMenu.setVisible(false);
                }
            }
        });
        return button;
    }

    private Component createPrintMenuItem() {
        JMenuItem menuItem = new JMenuItem("Print...");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().print();
            }
        });
        return menuItem;
    }

    private Component createPreferencesSubMenu() {
        JMenu menu = new JMenu("Preferences");
        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
        menu.add(createCheckBoxMenuItem("JavaScript Enabled", preferences.isJavaScriptEnabled(),
                new CheckBoxMenuItemCallback() {
                    public void call(boolean selected) {
                        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
                        preferences.setJavaScriptEnabled(selected);
                        browserView.getBrowser().setPreferences(preferences);
                        browserView.getBrowser().reloadIgnoringCache();
                    }
                }));
        menu.add(createCheckBoxMenuItem("Images Enabled", preferences.isImagesEnabled(),
                new CheckBoxMenuItemCallback() {
                    public void call(boolean selected) {
                        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
                        preferences.setImagesEnabled(selected);
                        browserView.getBrowser().setPreferences(preferences);
                        browserView.getBrowser().reloadIgnoringCache();
                    }
                }));
        menu.add(createCheckBoxMenuItem("Plugins Enabled", preferences.isPluginsEnabled(),
                new CheckBoxMenuItemCallback() {
                    public void call(boolean selected) {
                        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
                        preferences.setPluginsEnabled(selected);
                        browserView.getBrowser().setPreferences(preferences);
                        browserView.getBrowser().reloadIgnoringCache();
                    }
                }));
        menu.add(createCheckBoxMenuItem("JavaScript Can Access Clipboard",
                preferences.isJavaScriptCanAccessClipboard(), new CheckBoxMenuItemCallback() {
                    public void call(boolean selected) {
                        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
                        preferences.setJavaScriptCanAccessClipboard(selected);
                        browserView.getBrowser().setPreferences(preferences);
                        browserView.getBrowser().reloadIgnoringCache();
                    }
                }));
        menu.add(createCheckBoxMenuItem("JavaScript Can Open Windows",
                preferences.isJavaScriptCanOpenWindowsAutomatically(),
                new CheckBoxMenuItemCallback() {
                    public void call(boolean selected) {
                        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
                        preferences.setJavaScriptCanOpenWindowsAutomatically(selected);
                        browserView.getBrowser().setPreferences(preferences);
                        browserView.getBrowser().reloadIgnoringCache();
                    }
                }));
        return menu;
    }

    private Component createClearCacheMenuItem() {
        JMenuItem menuItem = new JMenuItem("Clear Cache");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().getCacheStorage().clearCache(new Callback() {
                    public void invoke() {
                        JOptionPane.showMessageDialog(browserView, "Cache is cleared successfully.",
                                "Clear Cache", JOptionPane.INFORMATION_MESSAGE);
                    }
                });
            }
        });
        return menuItem;
    }

    private Component createExecuteCommandSubMenu() {
        final JMenu menu = new JMenu("Execute Command");
        menu.addMenuListener(new MenuListener() {
            public void menuSelected(MenuEvent e) {
                Component[] menuItems = menu.getMenuComponents();
                for (Component menuItem : menuItems) {
                    menuItem.setEnabled(browserView.getBrowser()
                            .isCommandEnabled(((CommandMenuItem) menuItem).getCommand()));
                }
            }

            public void menuDeselected(MenuEvent e) {

            }

            public void menuCanceled(MenuEvent e) {

            }
        });

        menu.add(createExecuteCommandSubMenuItem("Cut", EditorCommand.CUT));
        menu.add(createExecuteCommandSubMenuItem("Copy", EditorCommand.COPY));
        menu.add(createExecuteCommandSubMenuItem("Paste", EditorCommand.PASTE));
        menu.add(createExecuteCommandSubMenuItem("Select All", EditorCommand.SELECT_ALL));
        menu.add(createExecuteCommandSubMenuItem("Unselect", EditorCommand.UNSELECT));
        menu.add(createExecuteCommandSubMenuItem("Undo", EditorCommand.UNDO));
        menu.add(createExecuteCommandSubMenuItem("Redo", EditorCommand.REDO));
        menu.add(createExecuteCommandSubMenuItem("Insert Text...", "Insert Text",
                EditorCommand.INSERT_TEXT));
        menu.add(createExecuteCommandSubMenuItem("Find Text...", "Find Text",
                EditorCommand.FIND_STRING));
        return menu;
    }

    private Component createExecuteCommandSubMenuItem(final String commandName,
            final EditorCommand command) {
        final CommandMenuItem menuItem = new CommandMenuItem(commandName, command);
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().executeCommand(command);
            }
        });
        return menuItem;
    }

    private Component createExecuteCommandSubMenuItem(final String commandName,
            final String dialogTitle, final EditorCommand command) {
        final CommandMenuItem menuItem = new CommandMenuItem(commandName, command);
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String value = JOptionPane
                        .showInputDialog(browserView, "Command value:", dialogTitle,
                                JOptionPane.PLAIN_MESSAGE);
                browserView.getBrowser().executeCommand(command, value);
            }
        });
        return menuItem;
    }

    private Component createMoreMenuItem() {
        JMenuItem menuItem = new JMenuItem("More Features...");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().loadURL(
                        "https://jxbrowser.support.teamdev.com/support/solutions/9000049010");
            }
        });
        return menuItem;
    }

    private Component createSaveWebPageMenuItem() {
        JMenuItem menuItem = new JMenuItem("Save Web Page...");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFileChooser fileChooser = new JFileChooser();
                fileChooser.setSelectedFile(new File("my-web-page.html"));
                int result = fileChooser.showSaveDialog(browserView);
                if (result == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = fileChooser.getSelectedFile();
                    String dirPath = new File(selectedFile.getParent(), "resources")
                            .getAbsolutePath();
                    browserView.getBrowser().saveWebPage(selectedFile.getAbsolutePath(), dirPath,
                            SavePageType.COMPLETE_HTML);
                }
            }
        });
        return menuItem;
    }

    private Component createActualSizeMenuItem() {
        JMenuItem menuItem = new JMenuItem("Actual Size");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().zoomReset();
            }
        });
        return menuItem;
    }

    private Component createZoomOutMenuItem() {
        JMenuItem menuItem = new JMenuItem("Zoom Out");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().zoomOut();
            }
        });
        return menuItem;
    }

    private Component createZoomInMenuItem() {
        JMenuItem menuItem = new JMenuItem("Zoom In");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().zoomIn();
            }
        });
        return menuItem;
    }

    private Component createHTML5VideoMenuItem() {
        JMenuItem menuItem = new JMenuItem("HTML5 Video");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser()
                        .loadURL("http://www.w3.org/2010/05/video/mediaevents.html");
            }
        });
        return menuItem;
    }

    private Component createGoogleMapsMenuItem() {
        JMenuItem menuItem = new JMenuItem("Google Maps");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().loadURL("https://maps.google.com/");
            }
        });
        return menuItem;
    }

    private Component createJavaScriptDialogsMenuItem() {
        JMenuItem menuItem = new JMenuItem("JavaScript Dialogs");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().loadURL("http://www.javascripter.net/faq/alert.htm");
            }
        });
        return menuItem;
    }

    private Component createDownloadFileMenuItem() {
        JMenuItem menuItem = new JMenuItem("Download File");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().loadURL(
                        "https://s3.amazonaws.com/cloud.teamdev.com/downloads/demo/jxbrowserdemo.jnlp");
            }
        });
        return menuItem;
    }

    private Component createGetHTMLMenuItem() {
        JMenuItem menuItem = new JMenuItem("Get HTML");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String html = browserView.getBrowser().getHTML();
                Window window = SwingUtilities.getWindowAncestor(browserView);
                JDialog dialog = new JDialog(window);
                dialog.setModal(true);
                dialog.setContentPane(new JScrollPane(new JTextArea(html)));
                dialog.setSize(700, 500);
                dialog.setLocationRelativeTo(null);
                dialog.setVisible(true);

            }
        });
        return menuItem;
    }

    private JMenuItem createConsoleMenuItem() {
        consoleMenuItem = new JMenuItem(RUN_JAVASCRIPT);
        consoleMenuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (RUN_JAVASCRIPT.equals(consoleMenuItem.getText())) {
                    consoleMenuItem.setText(CLOSE_JAVASCRIPT);
                    firePropertyChange("JSConsoleDisplayed", false, true);
                } else {
                    consoleMenuItem.setText(RUN_JAVASCRIPT);
                    firePropertyChange("JSConsoleClosed", false, true);
                }
            }
        });
        return consoleMenuItem;
    }

    private JMenuItem createUploadFileMenuItem() {
        JMenuItem menuItem = new JMenuItem("Upload File");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser()
                        .loadURL("http://www.cs.tut.fi/~jkorpela/forms/file.html#example");
            }
        });
        return menuItem;
    }

    private JMenuItem createPopupsMenuItem() {
        JMenuItem menuItem = new JMenuItem("Popup Windows");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().loadURL("http://www.popuptest.com");
            }
        });
        return menuItem;
    }

    private JMenuItem createPDFViewerMenuItem() {
        JMenuItem menuItem = new JMenuItem("PDF Viewer");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().loadURL("http://www.orimi.com/pdf-test.pdf");
            }
        });
        return menuItem;
    }

    private JMenuItem createFlashMenuItem() {
        JMenuItem menuItem = new JMenuItem("Adobe Flash");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                browserView.getBrowser().loadURL("http://helpx.adobe.com/flash-player.html");
            }
        });
        return menuItem;
    }

    /*private JMenuItem createAboutMenuItem() {
        JMenuItem menuItem = new JMenuItem("About JxBrowser Demo");
        menuItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                Frame parentFrame = (Frame) SwingUtilities.getWindowAncestor(ToolBar.this);
                AboutDialog aboutDialog = new AboutDialog(parentFrame);
                aboutDialog.setVisible(true);
            }
        });
        return menuItem;
    }*/

    private boolean isFocusRequired() {
        String url = addressBar.getText();
        return url.isEmpty() || url.equals(DEFAULT_URL);
    }

    @Override
    public void addNotify() {
        super.addNotify();
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                if (isFocusRequired()) {
                    addressBar.requestFocus();
                    addressBar.selectAll();
                }
            }
        });
    }

    private interface CheckBoxMenuItemCallback {
        void call(boolean selected);
    }

    private static class ActionButton extends JButton {
        private ActionButton(String hint, Action action) {
            super(action);
            setContentAreaFilled(false);
            setBorder(BorderFactory.createEmptyBorder());
            setBorderPainted(false);
            setRolloverEnabled(true);
            setToolTipText(hint);
            setText(null);
            setFocusable(false);
            setDefaultCapable(false);
        }
    }
}

sclass CommandMenuItem extends JMenuItem {

    private final EditorCommand command;

    public CommandMenuItem(String commandName, EditorCommand command) {
        super(commandName);
        this.command = command;
    }

    public EditorCommand getCommand() {
        return command;
    }
}

sclass JSConsole extends JPanel {

    private static final String NEW_LINE = "\n";
    private static final String QUERY_LINE_START = ">> ";
    private final Browser browser;
    private final ExecutorService executor;
    private JTextArea console;

    public JSConsole(Browser browser) {
        this.browser = browser;
        this.executor = Executors.newCachedThreadPool();
        setLayout(new BorderLayout());
        add(createTitle(), BorderLayout.NORTH);
        add(createConsoleOutput(), BorderLayout.CENTER);
        add(createConsoleInput(), BorderLayout.SOUTH);
    }

    private static JComponent createTitleLabel() {
        return new JLabel("JavaScript Console");
    }

    private JComponent createConsoleInput() {
        JPanel result = new JPanel(new BorderLayout());
        result.setBackground(Color.WHITE);

        JLabel label = new JLabel(QUERY_LINE_START);
        label.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 0));

        final JTextField consoleInput = new JTextField();
        consoleInput.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
        consoleInput.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                executor.submit(new Runnable() {
                    public void run() {
                        final String script = consoleInput.getText();
                        JSValue jsValue = browser.executeJavaScriptAndReturnValue(script);
                        final String executionResult = jsValue.toString();
                        SwingUtilities.invokeLater(new Runnable() {
                            public void run() {
                                updateConsoleOutput(script, executionResult);
                                consoleInput.setText("");
                            }
                        });
                    }
                });
            }
        });
        result.add(label, BorderLayout.WEST);
        result.add(consoleInput, BorderLayout.CENTER);
        return result;
    }

    private JComponent createConsoleOutput() {
        console = new JTextArea();
        console.setFont(new Font("Consolas", Font.PLAIN, 12));
        console.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
        console.setEditable(false);
        console.setWrapStyleWord(true);
        console.setLineWrap(true);
        console.setText("");
        JScrollPane scrollPane = new JScrollPane(console);
        scrollPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY));
        return scrollPane;
    }

    private JComponent createTitle() {
        JPanel panel = new JPanel(new BorderLayout());
//        panel.setBackground(new Color(182, 191, 207));
        panel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
        panel.add(createTitleLabel(), BorderLayout.WEST);
        panel.add(createCloseButton(), BorderLayout.EAST);
        return panel;
    }

    private JComponent createCloseButton() {
        JButton closeButton = new JButton();
        closeButton.setOpaque(false);
        closeButton.setToolTipText("Close JavaScript Console");
        closeButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
        closeButton.setPressedIcon(Resources.getIcon("close-pressed.png"));
        closeButton.setIcon(Resources.getIcon("close.png"));
        closeButton.setContentAreaFilled(false);
        closeButton.setFocusable(false);
        closeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                firePropertyChange("JSConsoleClosed", false, true);
            }
        });
        return closeButton;
    }

    private void updateConsoleOutput(String script, String executionResult) {
        displayScript(script);
        displayExecutionResult(executionResult);
        console.setCaretPosition(console.getText().length());
    }

    private void displayExecutionResult(String result) {
        console.append(result);
        console.append(NEW_LINE);
    }

    private void displayScript(String script) {
        console.append(QUERY_LINE_START);
        console.append(script);
        console.append(NEW_LINE);
    }
}

download  show line numbers  debug dex  old transpilations   

Travelled to 14 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, irmadwmeruwu, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

No comments. add comment

Snippet ID: #1016163
Snippet name: Tabbed JxBrowser [Include]
Eternal ID of this version: #1016163/12
Text MD5: f0be8ae90b5a7abad9e31b90981d48b0
Author: stefan
Category: javax / gui
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-07-05 11:14:13
Source code size: 44312 bytes / 1190 lines
Pitched / IR pitched: No / No
Views / Downloads: 425 / 766
Version history: 11 change(s)
Referenced in: #1016164 - Test JxBrowser in JInternalFrame with tabs [shortened, OK]
#1016166 - Java Chrome [Dyn Module, uses JxBrowser which needs a license]