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

1197
LINES

< > BotCompany Repo | #1016160 // Test JxBrowser in JInternalFrame with tabs [OK]

JavaX source code (desktop) [tags: use-pretranspiled] - run with: x30.jar

Download Jar. Uses 3874K of libraries. Click here for Pure Java version (6640L/45K).

1  
!7
2  
3  
lib 1400047 // jxbrowser icons
4  
5  
import com.teamdev.jxbrowser.chromium.demo.resources.Resources;
6  
import com.teamdev.jxbrowser.chromium.events.Callback;
7  
import com.teamdev.jxbrowser.chromium.*;
8  
import com.teamdev.jxbrowser.chromium.events.*;
9  
import com.teamdev.jxbrowser.chromium.internal.Environment;
10  
import com.teamdev.jxbrowser.chromium.swing.*;
11  
12  
import java.beans.*;
13  
14  
p-subst {
15  
  jxBrowser_init();
16  
  final JDesktopPane desktop = jDesktopPane();
17  
  showMaximizedFrame(desktop);
18  
  
19  
  swing {
20  
    final new TabbedPane tabbedPane;
21  
    tabbedPane.addAndSelectTab(TabFactory.createTab("http://BotCompany.de"));
22  
    tabbedPane.insertNewTabButton();
23  
  
24  
    onInternalFrameClosing(addInternalFrame(desktop, "Browser", tabbedPane),
25  
      r { tabbedPane.disposeAllTabs() });
26  
  }
27  
}
28  
29  
sclass TabbedPane extends JPanel {
30  
  private final List<Tab> tabs;
31  
  private final TabCaptions captions;
32  
  private final JComponent contentContainer;
33  
34  
  public TabbedPane() {
35  
      this.captions = new TabCaptions();
36  
      this.tabs = new ArrayList<Tab>();
37  
      this.contentContainer = new JPanel(new BorderLayout());
38  
39  
      setLayout(new BorderLayout());
40  
      add(captions, BorderLayout.NORTH);
41  
      add(contentContainer, BorderLayout.CENTER);
42  
  }
43  
  
44  
  void insertNewTabButton() {
45  
    TabButton button = new TabButton(Resources.getIcon("new-tab.png"), "New tab");
46  
    button.addActionListener(actionListener {
47  
      addAndSelectTab(TabFactory.createTab());
48  
    });
49  
    addTabButton(button);
50  
  }
51  
52  
  public void disposeAllTabs() {
53  
      for (Tab tab : getTabs()) {
54  
          disposeTab(tab);
55  
      }
56  
  }
57  
58  
  private void disposeTab(Tab tab) {
59  
      tab.getCaption().setSelected(false);
60  
      tab.getContent().dispose();
61  
      removeTab(tab);
62  
      if (hasTabs()) {
63  
          Tab firstTab = getFirstTab();
64  
          firstTab.getCaption().setSelected(true);
65  
      } else
66  
          disposeInternalFrame(this);
67  
  }
68  
69  
  private Tab findTab(TabCaption item) {
70  
      for (Tab tab : getTabs()) {
71  
          if (tab.getCaption().equals(item)) {
72  
              return tab;
73  
          }
74  
      }
75  
      return null;
76  
  }
77  
78  
79  
  void addAndSelectTab(Tab tab) {
80  
    addTab(tab);
81  
    selectTab(tab);
82  
  }
83  
84  
  public void addTab(final Tab tab) {
85  
      TabCaption caption = tab.getCaption();
86  
      caption.addPropertyChangeListener("CloseButtonPressed", new TabCaptionCloseTabListener());
87  
      caption.addPropertyChangeListener("TabSelected", new SelectTabListener());
88  
89  
      TabContent content = tab.getContent();
90  
      content.addPropertyChangeListener("TabClosed", new TabContentCloseTabListener());
91  
92  
      captions.addTab(caption);
93  
      tabs.add(tab);
94  
      validate();
95  
      repaint();
96  
  }
97  
98  
  private boolean hasTabs() {
99  
      return !tabs.isEmpty();
100  
  }
101  
102  
  private Tab getFirstTab() {
103  
      return tabs.get(0);
104  
  }
105  
106  
  private List<Tab> getTabs() {
107  
      return new ArrayList<Tab>(tabs);
108  
  }
109  
110  
  public void removeTab(Tab tab) {
111  
      TabCaption tabCaption = tab.getCaption();
112  
      captions.removeTab(tabCaption);
113  
      tabs.remove(tab);
114  
      validate();
115  
      repaint();
116  
  }
117  
118  
  public void addTabButton(TabButton button) {
119  
      captions.addTabButton(button);
120  
  }
121  
122  
  public void selectTab(Tab tab) {
123  
      TabCaption tabCaption = tab.getCaption();
124  
      TabCaption selectedTab = captions.getSelectedTab();
125  
      if (selectedTab != null && !selectedTab.equals(tabCaption)) {
126  
          selectedTab.setSelected(false);
127  
      }
128  
      captions.setSelectedTab(tabCaption);
129  
  }
130  
131  
  private class TabCaptionCloseTabListener implements PropertyChangeListener {
132  
      public void propertyChange(PropertyChangeEvent evt) {
133  
          TabCaption caption = (TabCaption) evt.getSource();
134  
          Tab tab = findTab(caption);
135  
          disposeTab(tab);
136  
      }
137  
  }
138  
139  
  private class SelectTabListener implements PropertyChangeListener {
140  
      public void propertyChange(PropertyChangeEvent evt) {
141  
          TabCaption caption = (TabCaption) evt.getSource();
142  
          Tab tab = findTab(caption);
143  
          if (caption.isSelected()) {
144  
              selectTab(tab);
145  
          }
146  
          if (!caption.isSelected()) {
147  
              TabContent content = tab.getContent();
148  
              contentContainer.remove(content);
149  
              contentContainer.validate();
150  
              contentContainer.repaint();
151  
          } else {
152  
              final TabContent content = tab.getContent();
153  
              contentContainer.add(content, BorderLayout.CENTER);
154  
              contentContainer.validate();
155  
              contentContainer.repaint();
156  
          }
157  
      }
158  
  }
159  
160  
  private class TabContentCloseTabListener implements PropertyChangeListener {
161  
      public void propertyChange(PropertyChangeEvent evt) {
162  
          TabContent content = (TabContent) evt.getSource();
163  
          Tab tab = findTab(content);
164  
          disposeTab(tab);
165  
      }
166  
167  
      private Tab findTab(TabContent content) {
168  
          for (Tab tab : getTabs()) {
169  
              if (tab.getContent().equals(content)) {
170  
                  return tab;
171  
              }
172  
          }
173  
          return null;
174  
      }
175  
  }
176  
}
177  
178  
static class TabFactory {
179  
180  
  public static Tab createTab() {
181  
      return createTab("about:blank");
182  
  }
183  
184  
  public static Tab createTab(String url) {
185  
      Browser browser = new Browser(BrowserType.LIGHTWEIGHT);
186  
      BrowserView browserView = new BrowserView(browser);
187  
      TabContent tabContent = new TabContent(browserView);
188  
189  
      browser.setDownloadHandler(new DefaultDownloadHandler(browserView));
190  
      browser.setDialogHandler(new DefaultDialogHandler(browserView));
191  
      browser.setPopupHandler(new DefaultPopupHandler());
192  
193  
      final TabCaption tabCaption = new TabCaption();
194  
      tabCaption.setTitle("about:blank");
195  
196  
      tabContent.addPropertyChangeListener("PageTitleChanged", new PropertyChangeListener() {
197  
          public void propertyChange(PropertyChangeEvent evt) {
198  
              tabCaption.setTitle((String) evt.getNewValue());
199  
          }
200  
      });
201  
202  
      browser.loadURL(url);
203  
      return new Tab(tabCaption, tabContent);
204  
  }
205  
}
206  
207  
sclass Tab {
208  
209  
    private final TabCaption caption;
210  
    private final TabContent content;
211  
212  
    public Tab(TabCaption caption, TabContent content) {
213  
        this.caption = caption;
214  
        this.content = content;
215  
    }
216  
217  
    public TabCaption getCaption() {
218  
        return caption;
219  
    }
220  
221  
    public TabContent getContent() {
222  
        return content;
223  
    }
224  
}
225  
226  
sclass TabButton extends JButton {
227  
228  
    public TabButton(Icon icon, String toolTipText) {
229  
        setIcon(icon);
230  
        setToolTipText(toolTipText);
231  
        setOpaque(false);
232  
        setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
233  
        setContentAreaFilled(false);
234  
        setFocusable(false);
235  
    }
236  
237  
}
238  
239  
sclass TabCaption extends JPanel {
240  
241  
    private boolean selected;
242  
    private TabCaptionComponent component;
243  
244  
    public TabCaption() {
245  
        setLayout(new BorderLayout());
246  
        setOpaque(false);
247  
        add(createComponent(), BorderLayout.CENTER);
248  
        add(Box.createHorizontalStrut(1), BorderLayout.EAST);
249  
    }
250  
251  
    private JComponent createComponent() {
252  
        component = new TabCaptionComponent();
253  
        component.addPropertyChangeListener("CloseButtonPressed", new PropertyChangeListener() {
254  
            public void propertyChange(PropertyChangeEvent evt) {
255  
                firePropertyChange("CloseButtonPressed", evt.getOldValue(), evt.getNewValue());
256  
            }
257  
        });
258  
        component.addPropertyChangeListener("TabClicked", new PropertyChangeListener() {
259  
            public void propertyChange(PropertyChangeEvent evt) {
260  
                setSelected(true);
261  
            }
262  
        });
263  
        return component;
264  
    }
265  
266  
    @Override
267  
    public Dimension getPreferredSize() {
268  
        return new Dimension(155, 26);
269  
    }
270  
271  
    @Override
272  
    public Dimension getMinimumSize() {
273  
        return new Dimension(50, 26);
274  
    }
275  
276  
    @Override
277  
    public Dimension getMaximumSize() {
278  
        return getPreferredSize();
279  
    }
280  
281  
    public void setTitle(String title) {
282  
        component.setTitle(title);
283  
    }
284  
285  
    public boolean isSelected() {
286  
        return selected;
287  
    }
288  
289  
    public void setSelected(boolean selected) {
290  
        boolean oldValue = this.selected;
291  
        this.selected = selected;
292  
        component.setSelected(selected);
293  
        firePropertyChange("TabSelected", oldValue, selected);
294  
    }
295  
296  
    private static class TabCaptionComponent extends JPanel {
297  
298  
        private final Color defaultBackground;
299  
        private JLabel label;
300  
301  
        private TabCaptionComponent() {
302  
            defaultBackground = getBackground();
303  
            setLayout(new BorderLayout());
304  
            setOpaque(false);
305  
            add(createLabel(), BorderLayout.CENTER);
306  
            add(createCloseButton(), BorderLayout.EAST);
307  
        }
308  
309  
        private JComponent createLabel() {
310  
            label = new JLabel();
311  
            label.setOpaque(false);
312  
            label.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
313  
            label.addMouseListener(new MouseAdapter() {
314  
                @Override
315  
                public void mousePressed(MouseEvent e) {
316  
                    if (e.getButton() == MouseEvent.BUTTON1) {
317  
                        firePropertyChange("TabClicked", false, true);
318  
                    }
319  
                    if (e.getButton() == MouseEvent.BUTTON2) {
320  
                        firePropertyChange("CloseButtonPressed", false, true);
321  
                    }
322  
                }
323  
            });
324  
            return label;
325  
        }
326  
327  
        private JComponent createCloseButton() {
328  
            JButton closeButton = new JButton();
329  
            closeButton.setOpaque(false);
330  
            closeButton.setToolTipText("Close");
331  
            closeButton.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
332  
            closeButton.setPressedIcon(Resources.getIcon("close-pressed.png"));
333  
            closeButton.setIcon(Resources.getIcon("close.png"));
334  
            closeButton.setContentAreaFilled(false);
335  
            closeButton.setFocusable(false);
336  
            closeButton.addActionListener(new ActionListener() {
337  
                public void actionPerformed(ActionEvent e) {
338  
                    firePropertyChange("CloseButtonPressed", false, true);
339  
                }
340  
            });
341  
            return closeButton;
342  
        }
343  
344  
        public void setTitle(final String title) {
345  
            SwingUtilities.invokeLater(new Runnable() {
346  
                public void run() {
347  
                    label.setText(title);
348  
                    label.setToolTipText(title);
349  
                }
350  
            });
351  
        }
352  
353  
        public void setSelected(boolean selected) {
354  
            setBackground(selected ? defaultBackground : new Color(150, 150, 150));
355  
            repaint();
356  
        }
357  
358  
        @Override
359  
        public void paint(Graphics g) {
360  
            Graphics2D g2d = (Graphics2D) g.create();
361  
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
362  
                    RenderingHints.VALUE_ANTIALIAS_ON);
363  
            g2d.setPaint(
364  
                    new GradientPaint(0, 0, Color.LIGHT_GRAY, 0, getHeight(), getBackground()));
365  
            g2d.fillRect(0, 0, getWidth(), getHeight());
366  
            g2d.dispose();
367  
            super.paint(g);
368  
        }
369  
    }
370  
}
371  
372  
sclass TabCaptions extends JPanel {
373  
374  
    private TabCaption selectedTab;
375  
376  
    private JPanel tabsPane;
377  
    private JPanel buttonsPane;
378  
379  
    public TabCaptions() {
380  
        createUI();
381  
    }
382  
383  
    private void createUI() {
384  
        setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
385  
        setBackground(Color.DARK_GRAY);
386  
        add(createItemsPane());
387  
        add(createButtonsPane());
388  
        add(Box.createHorizontalGlue());
389  
    }
390  
391  
    private JComponent createItemsPane() {
392  
        tabsPane = new JPanel();
393  
        tabsPane.setOpaque(false);
394  
        tabsPane.setLayout(new BoxLayout(tabsPane, BoxLayout.X_AXIS));
395  
        return tabsPane;
396  
    }
397  
398  
    private JComponent createButtonsPane() {
399  
        buttonsPane = new JPanel();
400  
        buttonsPane.setOpaque(false);
401  
        buttonsPane.setLayout(new BoxLayout(buttonsPane, BoxLayout.X_AXIS));
402  
        return buttonsPane;
403  
    }
404  
405  
    public void addTab(TabCaption item) {
406  
        tabsPane.add(item);
407  
    }
408  
409  
    public void removeTab(TabCaption item) {
410  
        tabsPane.remove(item);
411  
    }
412  
413  
    public void addTabButton(TabButton button) {
414  
        buttonsPane.add(button);
415  
    }
416  
417  
    public TabCaption getSelectedTab() {
418  
        return selectedTab;
419  
    }
420  
421  
    public void setSelectedTab(TabCaption selectedTab) {
422  
        this.selectedTab = selectedTab;
423  
        this.selectedTab.setSelected(true);
424  
    }
425  
}
426  
427  
sclass TabContent extends JPanel {
428  
429  
    private final BrowserView browserView;
430  
    private final ToolBar toolBar;
431  
    private final JComponent jsConsole;
432  
    private final JComponent container;
433  
    private final JComponent browserContainer;
434  
435  
    public TabContent(final BrowserView browserView) {
436  
        this.browserView = browserView;
437  
        this.browserView.getBrowser().addLoadListener(new LoadAdapter() {
438  
            @Override
439  
            public void onFinishLoadingFrame(FinishLoadingEvent event) {
440  
                if (event.isMainFrame()) {
441  
                    firePropertyChange("PageTitleChanged", null,
442  
                            TabContent.this.browserView.getBrowser().getTitle());
443  
                }
444  
            }
445  
        });
446  
447  
        this.browserView.getBrowser().addTitleListener(new TitleListener() {
448  
            @Override
449  
            public void onTitleChange(TitleEvent event) {
450  
                firePropertyChange("PageTitleChanged", null, event.getTitle());
451  
            }
452  
        });
453  
454  
        browserContainer = createBrowserContainer();
455  
        jsConsole = createConsole();
456  
        toolBar = createToolBar(browserView);
457  
458  
        container = new JPanel(new BorderLayout());
459  
        container.add(browserContainer, BorderLayout.CENTER);
460  
461  
        setLayout(new BorderLayout());
462  
        add(toolBar, BorderLayout.NORTH);
463  
        add(container, BorderLayout.CENTER);
464  
    }
465  
466  
    private ToolBar createToolBar(BrowserView browserView) {
467  
        ToolBar toolBar = new ToolBar(browserView);
468  
        toolBar.addPropertyChangeListener("TabClosed", new PropertyChangeListener() {
469  
            public void propertyChange(PropertyChangeEvent evt) {
470  
                firePropertyChange("TabClosed", false, true);
471  
            }
472  
        });
473  
        toolBar.addPropertyChangeListener("JSConsoleDisplayed", new PropertyChangeListener() {
474  
            public void propertyChange(PropertyChangeEvent evt) {
475  
                showConsole();
476  
            }
477  
        });
478  
        toolBar.addPropertyChangeListener("JSConsoleClosed", new PropertyChangeListener() {
479  
            public void propertyChange(PropertyChangeEvent evt) {
480  
                hideConsole();
481  
            }
482  
        });
483  
        return toolBar;
484  
    }
485  
486  
    private void hideConsole() {
487  
        showComponent(browserContainer);
488  
    }
489  
490  
    private void showComponent(JComponent component) {
491  
        container.removeAll();
492  
        container.add(component, BorderLayout.CENTER);
493  
        validate();
494  
    }
495  
496  
    private void showConsole() {
497  
        JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
498  
        splitPane.add(browserContainer, JSplitPane.TOP);
499  
        splitPane.add(jsConsole, JSplitPane.BOTTOM);
500  
        splitPane.setResizeWeight(0.8);
501  
        splitPane.setBorder(BorderFactory.createEmptyBorder());
502  
        showComponent(splitPane);
503  
    }
504  
505  
    private JComponent createConsole() {
506  
        JSConsole result = new JSConsole(browserView.getBrowser());
507  
        result.addPropertyChangeListener("JSConsoleClosed", new PropertyChangeListener() {
508  
            public void propertyChange(PropertyChangeEvent evt) {
509  
                hideConsole();
510  
                toolBar.didJSConsoleClose();
511  
            }
512  
        });
513  
        return result;
514  
    }
515  
516  
    private JComponent createBrowserContainer() {
517  
        JPanel container = new JPanel(new BorderLayout());
518  
        container.add(browserView, BorderLayout.CENTER);
519  
        return container;
520  
    }
521  
522  
    public void dispose() {
523  
        browserView.getBrowser().dispose();
524  
    }
525  
}
526  
527  
sclass ToolBar extends JPanel {
528  
    private static final String RUN_JAVASCRIPT = "Run JavaScript...";
529  
    private static final String CLOSE_JAVASCRIPT = "Close JavaScript Console";
530  
    private static final String DEFAULT_URL = "about:blank";
531  
    private final JTextField addressBar;
532  
    private final BrowserView browserView;
533  
    private JButton backwardButton;
534  
    private JButton forwardButton;
535  
    private JButton refreshButton;
536  
    private JButton stopButton;
537  
    private JMenuItem consoleMenuItem;
538  
539  
    public ToolBar(BrowserView browserView) {
540  
        this.browserView = browserView;
541  
        addressBar = createAddressBar();
542  
        setLayout(new GridBagLayout());
543  
        add(createActionsPane(),
544  
                new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST,
545  
                        GridBagConstraints.NONE, new Insets(0, 0, 0, 0), 0, 0));
546  
        add(addressBar, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0,
547  
                GridBagConstraints.WEST, GridBagConstraints.BOTH, new Insets(4, 0, 4, 5), 0, 0));
548  
        add(createMenuButton(), new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0,
549  
                GridBagConstraints.LINE_END, GridBagConstraints.HORIZONTAL, new Insets(0, 0, 0, 5),
550  
                0, 0));
551  
    }
552  
553  
    private static JButton createBackwardButton(final Browser browser) {
554  
        return createButton("Back", new AbstractAction() {
555  
            public void actionPerformed(ActionEvent e) {
556  
                browser.goBack();
557  
            }
558  
        });
559  
    }
560  
561  
    private static JButton createForwardButton(final Browser browser) {
562  
        return createButton("Forward", new AbstractAction() {
563  
            public void actionPerformed(ActionEvent e) {
564  
                browser.goForward();
565  
            }
566  
        });
567  
    }
568  
569  
    private static JButton createRefreshButton(final Browser browser) {
570  
        return createButton("Refresh", new AbstractAction() {
571  
            public void actionPerformed(ActionEvent e) {
572  
                browser.reload();
573  
            }
574  
        });
575  
    }
576  
577  
    private static JButton createStopButton(final Browser browser) {
578  
        return createButton("Stop", new AbstractAction() {
579  
            public void actionPerformed(ActionEvent e) {
580  
                browser.stop();
581  
            }
582  
        });
583  
    }
584  
585  
    private static JButton createButton(String caption, Action action) {
586  
        ActionButton button = new ActionButton(caption, action);
587  
        String imageName = caption.toLowerCase();
588  
        button.setIcon(Resources.getIcon(imageName + ".png"));
589  
        button.setRolloverIcon(Resources.getIcon(imageName + "-selected.png"));
590  
        return button;
591  
    }
592  
593  
    private static JCheckBoxMenuItem createCheckBoxMenuItem(String title, boolean selected,
594  
            final CheckBoxMenuItemCallback action) {
595  
        final JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(title, selected);
596  
        menuItem.addActionListener(new ActionListener() {
597  
            public void actionPerformed(ActionEvent e) {
598  
                action.call(menuItem.isSelected());
599  
            }
600  
        });
601  
        return menuItem;
602  
    }
603  
604  
    public void didJSConsoleClose() {
605  
        consoleMenuItem.setText(RUN_JAVASCRIPT);
606  
    }
607  
608  
    private JPanel createActionsPane() {
609  
        backwardButton = createBackwardButton(browserView.getBrowser());
610  
        forwardButton = createForwardButton(browserView.getBrowser());
611  
        refreshButton = createRefreshButton(browserView.getBrowser());
612  
        stopButton = createStopButton(browserView.getBrowser());
613  
614  
        JPanel actionsPanel = new JPanel();
615  
        actionsPanel.add(backwardButton);
616  
        actionsPanel.add(forwardButton);
617  
        actionsPanel.add(refreshButton);
618  
        actionsPanel.add(stopButton);
619  
        return actionsPanel;
620  
    }
621  
622  
    private JTextField createAddressBar() {
623  
        final JTextField result = new JTextField(DEFAULT_URL);
624  
        result.addActionListener(new ActionListener() {
625  
            public void actionPerformed(ActionEvent e) {
626  
                browserView.getBrowser().loadURL(result.getText());
627  
            }
628  
        });
629  
630  
        browserView.getBrowser().addLoadListener(new LoadAdapter() {
631  
            @Override
632  
            public void onStartLoadingFrame(StartLoadingEvent event) {
633  
                if (event.isMainFrame()) {
634  
                    SwingUtilities.invokeLater(new Runnable() {
635  
                        public void run() {
636  
                            refreshButton.setEnabled(false);
637  
                            stopButton.setEnabled(true);
638  
                        }
639  
                    });
640  
                }
641  
            }
642  
643  
            @Override
644  
            public void onProvisionalLoadingFrame(final ProvisionalLoadingEvent event) {
645  
                if (event.isMainFrame()) {
646  
                    SwingUtilities.invokeLater(new Runnable() {
647  
                        @Override
648  
                        public void run() {
649  
                            result.setText(event.getURL());
650  
                            result.setCaretPosition(result.getText().length());
651  
652  
                            Browser browser = event.getBrowser();
653  
                            forwardButton.setEnabled(browser.canGoForward());
654  
                            backwardButton.setEnabled(browser.canGoBack());
655  
                        }
656  
                    });
657  
                }
658  
            }
659  
660  
            @Override
661  
            public void onFinishLoadingFrame(final FinishLoadingEvent event) {
662  
                if (event.isMainFrame()) {
663  
                    SwingUtilities.invokeLater(new Runnable() {
664  
                        public void run() {
665  
                            refreshButton.setEnabled(true);
666  
                            stopButton.setEnabled(false);
667  
                        }
668  
                    });
669  
                }
670  
            }
671  
        });
672  
        return result;
673  
    }
674  
675  
    private JComponent createMenuButton() {
676  
        final JPopupMenu popupMenu = new JPopupMenu();
677  
        popupMenu.add(createConsoleMenuItem());
678  
        popupMenu.add(createGetHTMLMenuItem());
679  
        popupMenu.add(createPopupsMenuItem());
680  
        popupMenu.add(createUploadFileMenuItem());
681  
        popupMenu.add(createDownloadFileMenuItem());
682  
        popupMenu.add(createJavaScriptDialogsMenuItem());
683  
        popupMenu.add(createPDFViewerMenuItem());
684  
        popupMenu.add(createFlashMenuItem());
685  
        popupMenu.add(createGoogleMapsMenuItem());
686  
        popupMenu.add(createHTML5VideoMenuItem());
687  
        popupMenu.add(createZoomInMenuItem());
688  
        popupMenu.add(createZoomOutMenuItem());
689  
        popupMenu.add(createActualSizeMenuItem());
690  
        popupMenu.add(createSaveWebPageMenuItem());
691  
        popupMenu.add(createClearCacheMenuItem());
692  
        popupMenu.add(createPreferencesSubMenu());
693  
        popupMenu.add(createExecuteCommandSubMenu());
694  
        popupMenu.add(createPrintMenuItem());
695  
        popupMenu.addSeparator();
696  
        popupMenu.add(createMoreMenuItem());
697  
        popupMenu.addSeparator();
698  
        //popupMenu.add(createAboutMenuItem());
699  
700  
        final ActionButton button = new ActionButton("Preferences", null);
701  
        button.setIcon(Resources.getIcon("gear.png"));
702  
        button.addMouseListener(new MouseAdapter() {
703  
            public void mousePressed(MouseEvent e) {
704  
                if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
705  
                    popupMenu.show(e.getComponent(), 0, button.getHeight());
706  
                } else {
707  
                    popupMenu.setVisible(false);
708  
                }
709  
            }
710  
        });
711  
        return button;
712  
    }
713  
714  
    private Component createPrintMenuItem() {
715  
        JMenuItem menuItem = new JMenuItem("Print...");
716  
        menuItem.addActionListener(new ActionListener() {
717  
            public void actionPerformed(ActionEvent e) {
718  
                browserView.getBrowser().print();
719  
            }
720  
        });
721  
        return menuItem;
722  
    }
723  
724  
    private Component createPreferencesSubMenu() {
725  
        JMenu menu = new JMenu("Preferences");
726  
        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
727  
        menu.add(createCheckBoxMenuItem("JavaScript Enabled", preferences.isJavaScriptEnabled(),
728  
                new CheckBoxMenuItemCallback() {
729  
                    public void call(boolean selected) {
730  
                        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
731  
                        preferences.setJavaScriptEnabled(selected);
732  
                        browserView.getBrowser().setPreferences(preferences);
733  
                        browserView.getBrowser().reloadIgnoringCache();
734  
                    }
735  
                }));
736  
        menu.add(createCheckBoxMenuItem("Images Enabled", preferences.isImagesEnabled(),
737  
                new CheckBoxMenuItemCallback() {
738  
                    public void call(boolean selected) {
739  
                        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
740  
                        preferences.setImagesEnabled(selected);
741  
                        browserView.getBrowser().setPreferences(preferences);
742  
                        browserView.getBrowser().reloadIgnoringCache();
743  
                    }
744  
                }));
745  
        menu.add(createCheckBoxMenuItem("Plugins Enabled", preferences.isPluginsEnabled(),
746  
                new CheckBoxMenuItemCallback() {
747  
                    public void call(boolean selected) {
748  
                        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
749  
                        preferences.setPluginsEnabled(selected);
750  
                        browserView.getBrowser().setPreferences(preferences);
751  
                        browserView.getBrowser().reloadIgnoringCache();
752  
                    }
753  
                }));
754  
        menu.add(createCheckBoxMenuItem("JavaScript Can Access Clipboard",
755  
                preferences.isJavaScriptCanAccessClipboard(), new CheckBoxMenuItemCallback() {
756  
                    public void call(boolean selected) {
757  
                        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
758  
                        preferences.setJavaScriptCanAccessClipboard(selected);
759  
                        browserView.getBrowser().setPreferences(preferences);
760  
                        browserView.getBrowser().reloadIgnoringCache();
761  
                    }
762  
                }));
763  
        menu.add(createCheckBoxMenuItem("JavaScript Can Open Windows",
764  
                preferences.isJavaScriptCanOpenWindowsAutomatically(),
765  
                new CheckBoxMenuItemCallback() {
766  
                    public void call(boolean selected) {
767  
                        BrowserPreferences preferences = browserView.getBrowser().getPreferences();
768  
                        preferences.setJavaScriptCanOpenWindowsAutomatically(selected);
769  
                        browserView.getBrowser().setPreferences(preferences);
770  
                        browserView.getBrowser().reloadIgnoringCache();
771  
                    }
772  
                }));
773  
        return menu;
774  
    }
775  
776  
    private Component createClearCacheMenuItem() {
777  
        JMenuItem menuItem = new JMenuItem("Clear Cache");
778  
        menuItem.addActionListener(new ActionListener() {
779  
            public void actionPerformed(ActionEvent e) {
780  
                browserView.getBrowser().getCacheStorage().clearCache(new Callback() {
781  
                    public void invoke() {
782  
                        JOptionPane.showMessageDialog(browserView, "Cache is cleared successfully.",
783  
                                "Clear Cache", JOptionPane.INFORMATION_MESSAGE);
784  
                    }
785  
                });
786  
            }
787  
        });
788  
        return menuItem;
789  
    }
790  
791  
    private Component createExecuteCommandSubMenu() {
792  
        final JMenu menu = new JMenu("Execute Command");
793  
        menu.addMenuListener(new MenuListener() {
794  
            public void menuSelected(MenuEvent e) {
795  
                Component[] menuItems = menu.getMenuComponents();
796  
                for (Component menuItem : menuItems) {
797  
                    menuItem.setEnabled(browserView.getBrowser()
798  
                            .isCommandEnabled(((CommandMenuItem) menuItem).getCommand()));
799  
                }
800  
            }
801  
802  
            public void menuDeselected(MenuEvent e) {
803  
804  
            }
805  
806  
            public void menuCanceled(MenuEvent e) {
807  
808  
            }
809  
        });
810  
811  
        menu.add(createExecuteCommandSubMenuItem("Cut", EditorCommand.CUT));
812  
        menu.add(createExecuteCommandSubMenuItem("Copy", EditorCommand.COPY));
813  
        menu.add(createExecuteCommandSubMenuItem("Paste", EditorCommand.PASTE));
814  
        menu.add(createExecuteCommandSubMenuItem("Select All", EditorCommand.SELECT_ALL));
815  
        menu.add(createExecuteCommandSubMenuItem("Unselect", EditorCommand.UNSELECT));
816  
        menu.add(createExecuteCommandSubMenuItem("Undo", EditorCommand.UNDO));
817  
        menu.add(createExecuteCommandSubMenuItem("Redo", EditorCommand.REDO));
818  
        menu.add(createExecuteCommandSubMenuItem("Insert Text...", "Insert Text",
819  
                EditorCommand.INSERT_TEXT));
820  
        menu.add(createExecuteCommandSubMenuItem("Find Text...", "Find Text",
821  
                EditorCommand.FIND_STRING));
822  
        return menu;
823  
    }
824  
825  
    private Component createExecuteCommandSubMenuItem(final String commandName,
826  
            final EditorCommand command) {
827  
        final CommandMenuItem menuItem = new CommandMenuItem(commandName, command);
828  
        menuItem.addActionListener(new ActionListener() {
829  
            public void actionPerformed(ActionEvent e) {
830  
                browserView.getBrowser().executeCommand(command);
831  
            }
832  
        });
833  
        return menuItem;
834  
    }
835  
836  
    private Component createExecuteCommandSubMenuItem(final String commandName,
837  
            final String dialogTitle, final EditorCommand command) {
838  
        final CommandMenuItem menuItem = new CommandMenuItem(commandName, command);
839  
        menuItem.addActionListener(new ActionListener() {
840  
            public void actionPerformed(ActionEvent e) {
841  
                String value = JOptionPane
842  
                        .showInputDialog(browserView, "Command value:", dialogTitle,
843  
                                JOptionPane.PLAIN_MESSAGE);
844  
                browserView.getBrowser().executeCommand(command, value);
845  
            }
846  
        });
847  
        return menuItem;
848  
    }
849  
850  
    private Component createMoreMenuItem() {
851  
        JMenuItem menuItem = new JMenuItem("More Features...");
852  
        menuItem.addActionListener(new ActionListener() {
853  
            public void actionPerformed(ActionEvent e) {
854  
                browserView.getBrowser().loadURL(
855  
                        "https://jxbrowser.support.teamdev.com/support/solutions/9000049010");
856  
            }
857  
        });
858  
        return menuItem;
859  
    }
860  
861  
    private Component createSaveWebPageMenuItem() {
862  
        JMenuItem menuItem = new JMenuItem("Save Web Page...");
863  
        menuItem.addActionListener(new ActionListener() {
864  
            public void actionPerformed(ActionEvent e) {
865  
                JFileChooser fileChooser = new JFileChooser();
866  
                fileChooser.setSelectedFile(new File("my-web-page.html"));
867  
                int result = fileChooser.showSaveDialog(browserView);
868  
                if (result == JFileChooser.APPROVE_OPTION) {
869  
                    File selectedFile = fileChooser.getSelectedFile();
870  
                    String dirPath = new File(selectedFile.getParent(), "resources")
871  
                            .getAbsolutePath();
872  
                    browserView.getBrowser().saveWebPage(selectedFile.getAbsolutePath(), dirPath,
873  
                            SavePageType.COMPLETE_HTML);
874  
                }
875  
            }
876  
        });
877  
        return menuItem;
878  
    }
879  
880  
    private Component createActualSizeMenuItem() {
881  
        JMenuItem menuItem = new JMenuItem("Actual Size");
882  
        menuItem.addActionListener(new ActionListener() {
883  
            public void actionPerformed(ActionEvent e) {
884  
                browserView.getBrowser().zoomReset();
885  
            }
886  
        });
887  
        return menuItem;
888  
    }
889  
890  
    private Component createZoomOutMenuItem() {
891  
        JMenuItem menuItem = new JMenuItem("Zoom Out");
892  
        menuItem.addActionListener(new ActionListener() {
893  
            public void actionPerformed(ActionEvent e) {
894  
                browserView.getBrowser().zoomOut();
895  
            }
896  
        });
897  
        return menuItem;
898  
    }
899  
900  
    private Component createZoomInMenuItem() {
901  
        JMenuItem menuItem = new JMenuItem("Zoom In");
902  
        menuItem.addActionListener(new ActionListener() {
903  
            public void actionPerformed(ActionEvent e) {
904  
                browserView.getBrowser().zoomIn();
905  
            }
906  
        });
907  
        return menuItem;
908  
    }
909  
910  
    private Component createHTML5VideoMenuItem() {
911  
        JMenuItem menuItem = new JMenuItem("HTML5 Video");
912  
        menuItem.addActionListener(new ActionListener() {
913  
            public void actionPerformed(ActionEvent e) {
914  
                browserView.getBrowser()
915  
                        .loadURL("http://www.w3.org/2010/05/video/mediaevents.html");
916  
            }
917  
        });
918  
        return menuItem;
919  
    }
920  
921  
    private Component createGoogleMapsMenuItem() {
922  
        JMenuItem menuItem = new JMenuItem("Google Maps");
923  
        menuItem.addActionListener(new ActionListener() {
924  
            public void actionPerformed(ActionEvent e) {
925  
                browserView.getBrowser().loadURL("https://maps.google.com/");
926  
            }
927  
        });
928  
        return menuItem;
929  
    }
930  
931  
    private Component createJavaScriptDialogsMenuItem() {
932  
        JMenuItem menuItem = new JMenuItem("JavaScript Dialogs");
933  
        menuItem.addActionListener(new ActionListener() {
934  
            public void actionPerformed(ActionEvent e) {
935  
                browserView.getBrowser().loadURL("http://www.javascripter.net/faq/alert.htm");
936  
            }
937  
        });
938  
        return menuItem;
939  
    }
940  
941  
    private Component createDownloadFileMenuItem() {
942  
        JMenuItem menuItem = new JMenuItem("Download File");
943  
        menuItem.addActionListener(new ActionListener() {
944  
            public void actionPerformed(ActionEvent e) {
945  
                browserView.getBrowser().loadURL(
946  
                        "https://s3.amazonaws.com/cloud.teamdev.com/downloads/demo/jxbrowserdemo.jnlp");
947  
            }
948  
        });
949  
        return menuItem;
950  
    }
951  
952  
    private Component createGetHTMLMenuItem() {
953  
        JMenuItem menuItem = new JMenuItem("Get HTML");
954  
        menuItem.addActionListener(new ActionListener() {
955  
            public void actionPerformed(ActionEvent e) {
956  
                String html = browserView.getBrowser().getHTML();
957  
                Window window = SwingUtilities.getWindowAncestor(browserView);
958  
                JDialog dialog = new JDialog(window);
959  
                dialog.setModal(true);
960  
                dialog.setContentPane(new JScrollPane(new JTextArea(html)));
961  
                dialog.setSize(700, 500);
962  
                dialog.setLocationRelativeTo(null);
963  
                dialog.setVisible(true);
964  
965  
            }
966  
        });
967  
        return menuItem;
968  
    }
969  
970  
    private JMenuItem createConsoleMenuItem() {
971  
        consoleMenuItem = new JMenuItem(RUN_JAVASCRIPT);
972  
        consoleMenuItem.addActionListener(new ActionListener() {
973  
            public void actionPerformed(ActionEvent e) {
974  
                if (RUN_JAVASCRIPT.equals(consoleMenuItem.getText())) {
975  
                    consoleMenuItem.setText(CLOSE_JAVASCRIPT);
976  
                    firePropertyChange("JSConsoleDisplayed", false, true);
977  
                } else {
978  
                    consoleMenuItem.setText(RUN_JAVASCRIPT);
979  
                    firePropertyChange("JSConsoleClosed", false, true);
980  
                }
981  
            }
982  
        });
983  
        return consoleMenuItem;
984  
    }
985  
986  
    private JMenuItem createUploadFileMenuItem() {
987  
        JMenuItem menuItem = new JMenuItem("Upload File");
988  
        menuItem.addActionListener(new ActionListener() {
989  
            public void actionPerformed(ActionEvent e) {
990  
                browserView.getBrowser()
991  
                        .loadURL("http://www.cs.tut.fi/~jkorpela/forms/file.html#example");
992  
            }
993  
        });
994  
        return menuItem;
995  
    }
996  
997  
    private JMenuItem createPopupsMenuItem() {
998  
        JMenuItem menuItem = new JMenuItem("Popup Windows");
999  
        menuItem.addActionListener(new ActionListener() {
1000  
            public void actionPerformed(ActionEvent e) {
1001  
                browserView.getBrowser().loadURL("http://www.popuptest.com");
1002  
            }
1003  
        });
1004  
        return menuItem;
1005  
    }
1006  
1007  
    private JMenuItem createPDFViewerMenuItem() {
1008  
        JMenuItem menuItem = new JMenuItem("PDF Viewer");
1009  
        menuItem.addActionListener(new ActionListener() {
1010  
            public void actionPerformed(ActionEvent e) {
1011  
                browserView.getBrowser().loadURL("http://www.orimi.com/pdf-test.pdf");
1012  
            }
1013  
        });
1014  
        return menuItem;
1015  
    }
1016  
1017  
    private JMenuItem createFlashMenuItem() {
1018  
        JMenuItem menuItem = new JMenuItem("Adobe Flash");
1019  
        menuItem.addActionListener(new ActionListener() {
1020  
            public void actionPerformed(ActionEvent e) {
1021  
                browserView.getBrowser().loadURL("http://helpx.adobe.com/flash-player.html");
1022  
            }
1023  
        });
1024  
        return menuItem;
1025  
    }
1026  
1027  
    /*private JMenuItem createAboutMenuItem() {
1028  
        JMenuItem menuItem = new JMenuItem("About JxBrowser Demo");
1029  
        menuItem.addActionListener(new ActionListener() {
1030  
            public void actionPerformed(ActionEvent e) {
1031  
                Frame parentFrame = (Frame) SwingUtilities.getWindowAncestor(ToolBar.this);
1032  
                AboutDialog aboutDialog = new AboutDialog(parentFrame);
1033  
                aboutDialog.setVisible(true);
1034  
            }
1035  
        });
1036  
        return menuItem;
1037  
    }*/
1038  
1039  
    private boolean isFocusRequired() {
1040  
        String url = addressBar.getText();
1041  
        return url.isEmpty() || url.equals(DEFAULT_URL);
1042  
    }
1043  
1044  
    @Override
1045  
    public void addNotify() {
1046  
        super.addNotify();
1047  
        SwingUtilities.invokeLater(new Runnable() {
1048  
            public void run() {
1049  
                if (isFocusRequired()) {
1050  
                    addressBar.requestFocus();
1051  
                    addressBar.selectAll();
1052  
                }
1053  
            }
1054  
        });
1055  
    }
1056  
1057  
    private interface CheckBoxMenuItemCallback {
1058  
        void call(boolean selected);
1059  
    }
1060  
1061  
    private static class ActionButton extends JButton {
1062  
        private ActionButton(String hint, Action action) {
1063  
            super(action);
1064  
            setContentAreaFilled(false);
1065  
            setBorder(BorderFactory.createEmptyBorder());
1066  
            setBorderPainted(false);
1067  
            setRolloverEnabled(true);
1068  
            setToolTipText(hint);
1069  
            setText(null);
1070  
            setFocusable(false);
1071  
            setDefaultCapable(false);
1072  
        }
1073  
    }
1074  
}
1075  
1076  
sclass CommandMenuItem extends JMenuItem {
1077  
1078  
    private final EditorCommand command;
1079  
1080  
    public CommandMenuItem(String commandName, EditorCommand command) {
1081  
        super(commandName);
1082  
        this.command = command;
1083  
    }
1084  
1085  
    public EditorCommand getCommand() {
1086  
        return command;
1087  
    }
1088  
}
1089  
1090  
sclass JSConsole extends JPanel {
1091  
1092  
    private static final String NEW_LINE = "\n";
1093  
    private static final String QUERY_LINE_START = ">> ";
1094  
    private final Browser browser;
1095  
    private final ExecutorService executor;
1096  
    private JTextArea console;
1097  
1098  
    public JSConsole(Browser browser) {
1099  
        this.browser = browser;
1100  
        this.executor = Executors.newCachedThreadPool();
1101  
        setLayout(new BorderLayout());
1102  
        add(createTitle(), BorderLayout.NORTH);
1103  
        add(createConsoleOutput(), BorderLayout.CENTER);
1104  
        add(createConsoleInput(), BorderLayout.SOUTH);
1105  
    }
1106  
1107  
    private static JComponent createTitleLabel() {
1108  
        return new JLabel("JavaScript Console");
1109  
    }
1110  
1111  
    private JComponent createConsoleInput() {
1112  
        JPanel result = new JPanel(new BorderLayout());
1113  
        result.setBackground(Color.WHITE);
1114  
1115  
        JLabel label = new JLabel(QUERY_LINE_START);
1116  
        label.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 0));
1117  
1118  
        final JTextField consoleInput = new JTextField();
1119  
        consoleInput.setBorder(BorderFactory.createEmptyBorder(2, 4, 2, 4));
1120  
        consoleInput.addActionListener(new ActionListener() {
1121  
            public void actionPerformed(ActionEvent e) {
1122  
                executor.submit(new Runnable() {
1123  
                    public void run() {
1124  
                        final String script = consoleInput.getText();
1125  
                        JSValue jsValue = browser.executeJavaScriptAndReturnValue(script);
1126  
                        final String executionResult = jsValue.toString();
1127  
                        SwingUtilities.invokeLater(new Runnable() {
1128  
                            public void run() {
1129  
                                updateConsoleOutput(script, executionResult);
1130  
                                consoleInput.setText("");
1131  
                            }
1132  
                        });
1133  
                    }
1134  
                });
1135  
            }
1136  
        });
1137  
        result.add(label, BorderLayout.WEST);
1138  
        result.add(consoleInput, BorderLayout.CENTER);
1139  
        return result;
1140  
    }
1141  
1142  
    private JComponent createConsoleOutput() {
1143  
        console = new JTextArea();
1144  
        console.setFont(new Font("Consolas", Font.PLAIN, 12));
1145  
        console.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
1146  
        console.setEditable(false);
1147  
        console.setWrapStyleWord(true);
1148  
        console.setLineWrap(true);
1149  
        console.setText("");
1150  
        JScrollPane scrollPane = new JScrollPane(console);
1151  
        scrollPane.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, Color.GRAY));
1152  
        return scrollPane;
1153  
    }
1154  
1155  
    private JComponent createTitle() {
1156  
        JPanel panel = new JPanel(new BorderLayout());
1157  
//        panel.setBackground(new Color(182, 191, 207));
1158  
        panel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
1159  
        panel.add(createTitleLabel(), BorderLayout.WEST);
1160  
        panel.add(createCloseButton(), BorderLayout.EAST);
1161  
        return panel;
1162  
    }
1163  
1164  
    private JComponent createCloseButton() {
1165  
        JButton closeButton = new JButton();
1166  
        closeButton.setOpaque(false);
1167  
        closeButton.setToolTipText("Close JavaScript Console");
1168  
        closeButton.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
1169  
        closeButton.setPressedIcon(Resources.getIcon("close-pressed.png"));
1170  
        closeButton.setIcon(Resources.getIcon("close.png"));
1171  
        closeButton.setContentAreaFilled(false);
1172  
        closeButton.setFocusable(false);
1173  
        closeButton.addActionListener(new ActionListener() {
1174  
            public void actionPerformed(ActionEvent e) {
1175  
                firePropertyChange("JSConsoleClosed", false, true);
1176  
            }
1177  
        });
1178  
        return closeButton;
1179  
    }
1180  
1181  
    private void updateConsoleOutput(String script, String executionResult) {
1182  
        displayScript(script);
1183  
        displayExecutionResult(executionResult);
1184  
        console.setCaretPosition(console.getText().length());
1185  
    }
1186  
1187  
    private void displayExecutionResult(String result) {
1188  
        console.append(result);
1189  
        console.append(NEW_LINE);
1190  
    }
1191  
1192  
    private void displayScript(String script) {
1193  
        console.append(QUERY_LINE_START);
1194  
        console.append(script);
1195  
        console.append(NEW_LINE);
1196  
    }
1197  
}

Author comment

Began life as a copy of #1016155

download  show line numbers  debug dex  old transpilations   

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

No comments. add comment

Snippet ID: #1016160
Snippet name: Test JxBrowser in JInternalFrame with tabs [OK]
Eternal ID of this version: #1016160/23
Text MD5: e02570f7e9c299686eda85799db8a744
Transpilation MD5: eb68c59ac90c807b544c95f479c37ab7
Author: stefan
Category: javax / gui
Type: JavaX source code (desktop)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2018-06-07 19:37:31
Source code size: 44331 bytes / 1197 lines
Pitched / IR pitched: No / No
Views / Downloads: 861 / 1297
Version history: 22 change(s)
Referenced in: [show references]