exercise28_7.java

来自「java程序设计 机械工业出版社 书籍代码」· Java 代码 · 共 82 行

JAVA
82
字号
// Exercise28_7.java: View a remote text fileimport java.awt.*;import java.awt.event.*;import java.io.*;import java.net.*;import javax.swing.*;public class Exercise28_7 extends JApplet implements ActionListener {  // Button to view the file  private JButton jbtView = new JButton("View");  // Text field to receive file name  private JTextField jtf = new JTextField(12);  // Text area to store file  private JEditorPane jep = new JEditorPane();  // Label to display status  private JLabel jlblStatus = new JLabel();  // Initialize the applet  public void init() {    // Create a Panel to hold a label, a text field, and a button    Panel p1 = new Panel();    p1.setLayout(new BorderLayout());    p1.add(new JLabel("Filename"), BorderLayout.WEST);    p1.add(jtf, BorderLayout.CENTER);    p1.add(jbtView, BorderLayout.EAST);    // Place text area and panel p to the applet    getContentPane().setLayout(new BorderLayout());    getContentPane().add(new JScrollPane(jep), BorderLayout.CENTER);    getContentPane().add(p1, BorderLayout.NORTH);    getContentPane().add(jlblStatus, BorderLayout.SOUTH);    // Register listener    jbtView.addActionListener(this);  }  // Handle the "View" button  public void actionPerformed(ActionEvent e) {    if (e.getSource() == jbtView)      showFile();  }  private void showFile() {    try {      // Get the URL from text field      URL url = new URL(jtf.getText().trim());      // Display the HTML file      jep.setPage(url);      jlblStatus.setText("File loaded successfully");    }    catch (IOException ex) {      jlblStatus.setText(ex.getMessage());    }  }  // Main method  public static void main(String[] args) {    // Create a frame    JFrame frame = new JFrame(      "Exercise28_7: Display HTML File From a Web Server");    // Create an instance of MortgageApplet    Exercise28_7 applet = new Exercise28_7();    // Add the applet instance to the frame    frame.getContentPane().add(applet, BorderLayout.CENTER);    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    // Invoke init() and start()    applet.init();    applet.start();    // Display the frame    frame.setSize(300, 300);    frame.setVisible(true);  }}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?