Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Java How to Program, Fourth Edition - Deitel H., Deitel P.pdf
Скачиваний:
58
Добавлен:
24.05.2014
Размер:
14.17 Mб
Скачать

986

Networking

Chapter 17

window to display the content from the specified URI. The target frame _self specifies that the content from the specified URI should be displayed in the same frame as the applet (the applet’s HTML page is replaced in this case). The target frame _top specifies that the browser should remove the current frames in the browser window, then display the content from the specified URI in the current window. For more information on HTML and frames, see the World Wide Web Consortium (W3C) Web site

http://www.w3.org

[Note: This applet must be run from a World Wide Web browser, such as Netscape Navigator or Microsoft Internet Explorer, to see the results of displaying another Web page. The appletviewer is capable only of executing applets—it ignores all other HTML tags. If the Web sites in the program contained Java applets, only those applets would appear in the appletviewer when the user selects a Web site. Each applet would execute in a separate appletviewer window. Of the browsers mentioned here, only Netscape Navigator 6 currently supports the features of Java 2. You will need to use the Java Plug-in (discussed in Chapter 3) to execute this applet in Microsoft Internet Explorer or older versions of Netscape Navigator.]

17.3 Reading a File on a Web Server

The application of Fig. 17.3 uses Swing GUI component JEditorPane (from package javax.swing) to display the contents of a file on a Web server. The user inputs the URI in the JTextField at the top of the window, and the program displays the corresponding document (if it exists) in the JEditorPane. Class JEditorPane is able to render both plain text and HTML-formatted text, so this application acts as a simple Web browser. The application also demonstrates how to process HyperlinkEvents when the user clicks a hyperlink in the HTML document. The screen captures in Fig. 17.3 illustrate that the JEditorPane can display both simple text (the first screen) and HTML text (the second screen). The techniques shown in this example also can be used in applets. However, applets are allowed to read files only on the server from which the applet was downloaded.

1// Fig. 17.3: ReadServerFile.java

2 // This program uses a JEditorPane to display the 3 // contents of a file on a Web server.

4

5 // Java core packages

6import java.awt.*;

7 import java.awt.event.*;

8 import java.net.*;

9 import java.io.*;

10

11// Java extension packages

12import javax.swing.*;

13import javax.swing.event.*;

15public class ReadServerFile extends JFrame {

16private JTextField enterField;

17private JEditorPane contentsArea;

Fig. 17.3 Reading a file by opening a connection through a URL (part 1 of 4)

Chapter 17

Networking

987

18

19// set up GUI

20public ReadServerFile()

21{

22super( "Simple Web Browser" );

24 Container container = getContentPane();

25

26// create enterField and register its listener

27enterField = new JTextField( "Enter file URL here" );

29

enterField.addActionListener(

30

 

31

new ActionListener() {

32

 

33

// get document specified by user

34

public void actionPerformed( ActionEvent event )

35

{

36

getThePage( event.getActionCommand() );

37

}

38

 

39

} // end anonymous inner class

40

 

41

); // end call to addActionListener

42

 

43

container.add( enterField, BorderLayout.NORTH );

44

 

45// create contentsArea and register HyperlinkEvent listener

46contentsArea = new JEditorPane();

47contentsArea.setEditable( false );

48

 

49

contentsArea.addHyperlinkListener(

50

 

51

new HyperlinkListener() {

52

 

53

// if user clicked hyperlink, go to specified page

54

public void hyperlinkUpdate( HyperlinkEvent event )

55

{

56

if ( event.getEventType() ==

57

HyperlinkEvent.EventType.ACTIVATED )

58

getThePage( event.getURL().toString() );

59

}

60

 

61

} // end anonymous inner class

62

 

63

); // end call to addHyperlinkListener

64

 

65

container.add( new JScrollPane( contentsArea ),

66

BorderLayout.CENTER );

67

 

68setSize( 400, 300 );

69setVisible( true );

70}

Fig. 17.3 Reading a file by opening a connection through a URL (part 2 of 4)

988

Networking

Chapter 17

71

72// load document; change mouse cursor to indicate status

73private void getThePage( String location )

74{

75// change mouse cursor to WAIT_CURSOR

76setCursor( Cursor.getPredefinedCursor(

77

Cursor.WAIT_CURSOR ) );

78

 

79// load document into contentsArea and display location in

80// enterField

81try {

82

contentsArea.setPage( location );

83enterField.setText( location );

84}

85

86// process problems loading document

87catch ( IOException ioException ) {

88

JOptionPane.showMessageDialog( this,

89

"Error retrieving specified URL",

90

"Bad URL", JOptionPane.ERROR_MESSAGE );

91

}

92

 

93

setCursor( Cursor.getPredefinedCursor(

94Cursor.DEFAULT_CURSOR ) );

95}

96

97// begin application execution

98public static void main( String args[] )

99{

100 ReadServerFile application = new ReadServerFile();

101

102 application.setDefaultCloseOperation(

103JFrame.EXIT_ON_CLOSE );

104}

105

106 } // end class ReadServerFile

Fig. 17.3 Reading a file by opening a connection through a URL (part 3 of 4)

Chapter 17

Networking

989

 

 

 

 

 

 

Fig. 17.3 Reading a file by opening a connection through a URL (part 4 of 4)

The application class ReadServerFile contains JTextField enterField, in which the user enters the URI of the file to read and JEditorPane contentsArea to display the contents of the file. When the user presses the Enter key in the JTextField, the program calls method actionPerformed (lines 34–37). Line 36 uses ActionEvent method getActionCommand to get the String the user input in the JTextField and passes that string to utility method getThePage (lines 73–95).

Lines 76–77 in method getThePage use method setCursor (inherited into class JFrame from class Component) to change the mouse cursor to the wait cursor (normally, an hourglass or a watch). If the file being downloaded is large, the wait cursor indicates to the user that the program is performing a task and that the user should wait for the task to complete. The static Cursor method getPredefinedCursor receives an integer indicating the cursor type (Cursor.WAIT_CURSOR in this case). See the API documentation for class Cursor for a complete list of cursors.

Line 82 uses JEditorPane method setPage to download the document specified by location and display it in the JEditorPane contents. If there is an error downloading the document, method setPage throws an IOException. Also, if an invalid URL is specified, a MalformedURLException (a sublcass of IOException) occurs. If the document loads successfully, line 83 displays the current location in enterField.

Lines 93–94 sets the Cursor back to Cursor.DEFAULT_CURSOR (the default Cursor) to indicate that the document download is complete.

Typically, an HTML document contains hyperlinks—text, images or GUI components which, when clicked, provide quick access to another document on the Web. If a JEditorPane contains an HTML document and the user clicks a hyperlink, the JEditorPane generates a HyperlinkEvent (package javax.swing.event) and notifies all registered HyperlinkListeners (package javax.swing.event) of that event. Lines 49–63 register a HyperlinkListener to handle HyperlinkEvents. When a HyperlinkEvent occurs, the program calls method hyperlinkUpdate (lines 54–