The following code shows you a basic GUI browser which loads the site and displays in JEditorPane.
Code
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.util.*;
public class Browser extends JFrame {
private JButton btnGo;
private JTextField txtAddress;
private JEditorPane editorPane;
private JLabel addressLabel;
Container con;
public void createComponents() {
//Loading ImageIcon File
Icon goIcon = new ImageIcon("Right.png");
btnGo = new JButton("Go");
btnGo.setPreferredSize( new Dimension (53,36) );
//Setting loaded image to button
btnGo.setIcon(goIcon);
//Setting text on button If mouse is hover on it
btnGo.setToolTipText("Go");
txtAddress = new JTextField();
txtAddress.setEditable(true);
txtAddress.setPreferredSize(new Dimension(425,36));
txtAddress.setFont(new Font("Comic Sans" , Font.ITALIC , 26));
editorPane = new JEditorPane();
editorPane.setEditable(false);
editorPane.setPreferredSize(new Dimension(1000,630));
addressLabel = new JLabel("Enter Address");
}
public void createGUI() {
con = getContentPane();
con.setLayout(new FlowLayout());
createComponents();
con.add(addressLabel);
con.add(txtAddress);
con.add(btnGo);
con.add(editorPane);
con.add(new JScrollPane(editorPane));
con.setBackground(Color.lightGray);
setSize(640,480);
setVisible(true);
setBackground(Color.white);
//Setting text of Window/Frame
setTitle("Browser");
//Cant maximize the frame
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//If user press button after writing site address
btnGo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
loadPage(txtAddress.getText());
}
});
//If user pressed enter after writing site address
txtAddress.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent ke) {
if (ke.getKeyCode() == KeyEvent.VK_ENTER) {
loadPage(txtAddress.getText());
}
}
});
}
public Browser() {
createGUI();
}
public void loadPage(String address) {
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
URL siteAddress = new URL("http://" + address);
editorPane.setPage(siteAddress);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Unable To Load Page");
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
public class Test {
public static void main(String[] args) {
new Browser();
}
}
0 comments:
Post a Comment