在java swing中使用嵌入式javafx制作带标签的Web浏览器

时间:2016-01-04 17:36:01

标签: java swing browser tabs javafx-8

我想使用java swing制作一个标签式网页浏览器,而javafx我现在在 java swing 中使用嵌入式javafx 进行了一些代码我想将其设置为标签式网页浏览器,以便我能够在我的网络浏览器中打开多标签

  

问题是每当我添加新标签选项时,它都会打开新标签页   但它覆盖了上一个标签(意味着它删除了最后一个标签并打开   同一窗口中的新内容。)

请告诉我正确的方法在我的网络浏览器中添加多标签选项 我的浏览器代码是:

package mybrowser; 
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.embed.swing.JFXPanel;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import java.net.URL;
import static javafx.concurrent.Worker.State.FAILED;

public class MyBrowser extends JFrame {

private final JFXPanel jfxPanel = new JFXPanel();
private WebEngine engine;

private final JPanel panel = new JPanel(new BorderLayout());
private final JLabel lblStatus = new JLabel();


private final JButton btnGo = new JButton("Go");
private final JTextField txtURL = new JTextField();
private final JProgressBar progressBar = new JProgressBar();

public MyBrowser() {
    super();
    initComponents();
}


private void initComponents() {
    createScene();

    ActionListener al = new ActionListener() {
        @Override 
        public void actionPerformed(ActionEvent e) {
            loadURL(txtURL.getText());
        }
    };

    btnGo.addActionListener(al);
    txtURL.addActionListener(al);

    progressBar.setPreferredSize(new Dimension(150, 18));
    progressBar.setStringPainted(true);

    JPanel topBar = new JPanel(new BorderLayout(5, 0));
    topBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
    topBar.add(txtURL, BorderLayout.CENTER);
    topBar.add(btnGo, BorderLayout.EAST);

    JPanel statusBar = new JPanel(new BorderLayout(5, 0));
    statusBar.setBorder(BorderFactory.createEmptyBorder(3, 5, 3, 5));
    statusBar.add(lblStatus, BorderLayout.CENTER);
    statusBar.add(progressBar, BorderLayout.EAST);

    panel.add(topBar, BorderLayout.NORTH);
    panel.add(jfxPanel, BorderLayout.CENTER);
    panel.add(statusBar, BorderLayout.SOUTH);

    getContentPane().add(panel);

    setPreferredSize(new Dimension(1024, 600));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    pack();

}

private void createScene() {

    Platform.runLater(new Runnable() {
        @Override 
        public void run() {

            WebView view = new WebView();
            engine = view.getEngine();

            engine.titleProperty().addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override 
                        public void run() {
                            MyBrowser.this.setTitle(newValue);
                        }
                    });
                }
            });

            engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {
                @Override 
                public void handle(final WebEvent<String> event) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override 
                        public void run() {
                            lblStatus.setText(event.getData());
                        }
                    });
                }
            });

            engine.locationProperty().addListener(new ChangeListener<String>() {
                @Override
                public void changed(ObservableValue<? extends String> ov, String oldValue, final String newValue) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override 
                        public void run() {
                            txtURL.setText(newValue);
                        }
                    });
                }
            });

            engine.getLoadWorker().workDoneProperty().addListener(new ChangeListener<Number>() {
                @Override
                public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {
                    SwingUtilities.invokeLater(new Runnable() {
                        @Override 
                        public void run() {
                            progressBar.setValue(newValue.intValue());
                        }
                    });
                }
            });

            engine.getLoadWorker()
                    .exceptionProperty()
                    .addListener(new ChangeListener<Throwable>() {

                        public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {
                            if (engine.getLoadWorker().getState() == FAILED) {
                                SwingUtilities.invokeLater(new Runnable() {
                                    @Override public void run() {
                                        JOptionPane.showMessageDialog(
                                                panel,
                                                (value != null) ?
                                                engine.getLocation() + "\n" + value.getMessage() :
                                                engine.getLocation() + "\nUnexpected error.",
                                                "Loading error...",
                                                JOptionPane.ERROR_MESSAGE);
                                    }
                                });
                            }
                        }
                    });

            jfxPanel.setScene(new Scene(view));
        }
    });
}

public void loadURL(final String url) {
    Platform.runLater(new Runnable() {
        @Override 
        public void run() {
            String tmp = toURL(url);

            if (tmp == null) {
                tmp = toURL("http://" + url);
            }

            engine.load(tmp);
        }
    });
}

private static String toURL(String str) {
    try {
        return new URL(str).toExternalForm();
    } catch (MalformedURLException exception) {
            return null;
    }
}



public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {

        public void run() {
            MyBrowser browser = new MyBrowser();
            browser.setVisible(true);
            browser.loadURL("http://google.com");
       }     
   });
}

}

1 个答案:

答案 0 :(得分:1)

嘿,我有另一种方法可以做你的项目,但它只在javafx中

    package myweb;

import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Tab;
import javafx.scene.control.TabPane;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;


public class Myweb extends Application {

    @Override
    public void start(Stage primaryStage) {
     Group root = new Group();
     BorderPane borderPane = new BorderPane();
        TabPane tb=new TabPane();
        tb.setPrefSize(1365, 768);
        //tb.setSide(Side.TOP);
        Createfirsttab(tb);
        final Tab newtab = new Tab();  
        newtab.setText(" + ");  
        newtab.setClosable(false);
        tb.getTabs().addAll(newtab);

        ScrollPane sp = new ScrollPane();

        tb.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<Tab>() {  
                @Override  
                public void changed(ObservableValue<? extends Tab> observable,  
                          Tab oldSelectedTab, Tab newSelectedTab) {  
                     if (newSelectedTab == newtab) {  
                          Tab tab = new Tab();  
                          tab.setText("        ");  
                          //WebView - to display, browse web pages.  
                          WebView webView = new WebView();  
                          final WebEngine webEngine = webView.getEngine();  
                          //webEngine.load(DEFAULT_URL);  
                          final TextField urlField = new TextField("http://");  
                          webEngine.locationProperty().addListener(new ChangeListener<String>() {  
                               @Override public void changed(ObservableValue<? extends String> observable, String oldValue, String newValue) {  
                                    urlField.setText(newValue);  
                               }  
                          });  
                          //Action definition for the Button Go.  
                          EventHandler<ActionEvent> goAction = new EventHandler<ActionEvent>() {  
                               @Override public void handle(ActionEvent event) {  
                                    webEngine.load(urlField.getText().startsWith("http://")   
                                              ? urlField.getText()   
                                                        : "http://" + urlField.getText());  
                               }  
                          };
                          urlField.setOnAction(goAction);  
                          Button goButton = new Button("Go");    
                          goButton.setOnAction(goAction);

                          HBox hBox = new HBox(5);  
                          hBox.getChildren().setAll(urlField, goButton);  
                          HBox.setHgrow(urlField, Priority.ALWAYS);  
                          final VBox vBox = new VBox(5);
                          sp.setContent(webView);
                          vBox.getChildren().setAll(hBox, sp);  
                          VBox.setVgrow(webView, Priority.ALWAYS);  
                          tab.setContent(vBox);
                          final ObservableList<Tab> tabs = tb.getTabs();  
                          tab.closableProperty().bind(Bindings.size(tabs).greaterThan(2));  
                          tabs.add(tabs.size() - 1, tab);
                          //tb.getTabs().add(tab);


                          tb.getSelectionModel().select(tab);



                     }
                      }

           });

        borderPane.setCenter(tb);
        root.getChildren().add(borderPane);
        Scene scene = new Scene(root, 1200, 600);

        primaryStage.setTitle("Wellcome");
        primaryStage.setScene(scene);
        primaryStage.show();
    }






    public static void main(String[] args) {
        launch(args);
    }




    private Tab Createfirsttab(TabPane tb) {
        Tab stab =new Tab(" Wellcome ");
        Label label = new Label();
        label.setText("\n\t\t\t To start browsing, click on New Tab.");  
           label.setFont(Font.font("Arial", FontWeight.BOLD, 20));  
           stab.setContent(label);
           tb.getTabs().add(stab);
           tb.getSelectionModel().select(stab);

           return stab;  
    }


}

使用它作为你的项目不要复杂。