Linux programming unleash phần 8 ppsx

84 292 0
Linux programming unleash phần 8 ppsx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

The only thing at all complicated about this example is handling the events associated with the user clicking on the button object. However, these events are handled with only a few lines of code in the same way that we handled events in the AWT example pro- gram in Listing 32.9: countButton.addMouseListener( new java.awt.event.MouseAdapter() { public void mouseClicked(MouseEvent e) { countLabel.setText(“button clicked “ + ++count + “ times”); } }); The addMouseListener method is used to associate an instance of the MouseListener with a button (or any other component). Now, it is possible to define a separate class that implements the MouseListener listener interface (which requires defining five methods: mouseClicked, mouseEntered, mouseExited, mousePressed, and mouseReleased). However, there is a MouseAdapter utility class that defines “do nothing” versions of these five methods. In this code example, we are creating an anonymous inner class (for example, it is an inner class with no name associated with it) that overrides the mouseClicked. Our mouseClicked method uses the setText method to change the dis- played text of a label. In Listing 32.13 we import all classes and interfaces from the packages java.awt (for the graphic components and containers) and java.awt.event (for the event-handling classes and interfaces), and from the package javax.swing to get the Swing (or JFC) classes. In Listing 32.11, we define a static public main method that is executed when we compile and run this sample program by typing: javac JFCSample.java java JFCSample The JFCSample program does not handle window closing events, so it must be terminated by typing Ctrl+C in the terminal window where you run the program. Writing a Chat Program Using JFC We will develop the ChatJFC program in this section. It is almost identical to the ChatAWT program, only it uses the JFC classes instead of the AWT classes. Both pro- grams were shown in Figure 32.2. The sample program in Listing 32.12 that implements a chat client using JFC is a little complex because the user interface has several components. Each component is posi- tioned by an X-Y location in a panel and is sized to a specific width and height using the setBounds method. Before looking at the code in Listing 32.12, you should look at the Programming the User Interface P ART IV 590 3772316072 CH32 7/26/99 2:05 PM Page 590 bottom of Figure 32.2, which shows the ChatJFC program running. The ChatJFC pro- gram uses the ChatEngine class. The interface to ChatEngine is very simple and was covered in a previous section. The ChatJFC class implements the ChatListener interface and registers itself with an instance of ChatEngine. This registration allows the chat engine object to call the receiveText method (required to implement the ChatListener interface) in the ChatJFC class. Listing 32.12 THE ChatJFC.java FILE // File: ChatJFC.java import javax.swing.*; // swing 1.1 //import com.sun.java.swing.*; // swing 1.0 import java.awt.*; import java.awt.event.*; public class ChatJFC extends JFrame implements ChatListener{ JPanel jPanel1 = new JPanel(); JTextField myPortField = new JTextField(); JLabel label1 = new JLabel(); JLabel label2 = new JLabel(); JTextField hostField = new JTextField(); JLabel label3 = new JLabel(); JTextField portField = new JTextField(); JLabel label4 = new JLabel(); JTextField inputField = new JTextField(); JLabel label5 = new JLabel(); JButton listenButton = new JButton(); JButton connectButton = new JButton(); JButton disconnectButton = new JButton(); JButton quitButton = new JButton(); JTextArea outputField = new JTextArea(); JScrollPane jScrollPane1 = new JScrollPane(); protected ChatEngine chatEngine; public ChatJFC() { super(“Chat with JFC GUI”); chatEngine = new ChatEngine(); chatEngine.registerChatListener(this); this.setSize(575, 348); setVisible(true); jPanel1.setLayout(null); jPanel1.setBounds(5, 16, 595, 343); outputField.setRows(500); jScrollPane1.setBounds(66, 92, 498, 168); this.getContentPane().setLayout(null); quitButton.setBounds(448, 280, 121, 32); GUI Programming Using Java C HAPTER 32 591 32 GUI PROGRAMMING U SING JAVA continues 3772316072 CH32 7/26/99 2:05 PM Page 591 Listing 32.12 CONTINUED quitButton.addMouseListener( new java.awt.event.MouseAdapter() { public void mouseClicked(MouseEvent e) { System.exit(0); } }); quitButton.setLabel(“Quit”); this.setSize(592, 371); label1.setFont(new Font(“Dialog”, 1, 12)); label1.setBounds(1, 5, 69, 33); label1.setText(“My port”); myPortField.setBounds(62, 11, 100, 24); myPortField.setText(“8000”); label2.setFont(new Font(“Dialog”, 1, 12)); label2.setBounds(200, 3, 93, 38); label2.setText(“Remote host”); hostField.setBounds(299, 7, 129, 27); hostField.setText(“localhost”); label3.setFont(new Font(“Dialog”, 1, 12)); label3.setBounds(433, 5, 45, 36); label3.setText(“Port”); portField.setBounds(469, 9, 93, 27); portField.setText(“8192”); label4.setFont(new Font(“Dialog”, 1, 12)); label4.setBounds(4, 43, 60, 28); label4.setText(“Input”); inputField.setBounds(65, 47, 507, 34); inputField.setText(“ “); inputField.addKeyListener( new java.awt.event.KeyAdapter() { public void keyPressed(KeyEvent e) { if (e.getKeyCode() == ‘\n’) { chatEngine.send(inputField.getText()); } } }); label5.setFont(new Font(“Dialog”, 1, 12)); label5.setBounds(0, 90, 58, 34); label5.setText(“Output”); listenButton.setBounds(5, 281, 163, 33); listenButton.setLabel(“Start listening”); listenButton.addMouseListener( new java.awt.event.MouseAdapter() { public void mouseClicked(MouseEvent e) { chatEngine.startListening( Integer.parseInt(myPortField.getText())); } }); Programming the User Interface P ART IV 592 3772316072 CH32 7/26/99 2:05 PM Page 592 connectButton.setBounds(175, 280, 136, 34); connectButton.addMouseListener( new java.awt.event.MouseAdapter() { public void mouseClicked(MouseEvent e) { chatEngine.connect(hostField.getText(), Integer.parseInt(portField.getText())); } }); connectButton.setLabel(“Connect”); disconnectButton.setBounds(315, 280, 127, 33); disconnectButton.addMouseListener( new java.awt.event.MouseAdapter() { public void mouseClicked(MouseEvent e) { chatEngine.connect(hostField.getText(), Integer.parseInt(portField.getText())); } }); disconnectButton.setLabel(“Disconnect”); this.getContentPane().add(jPanel1, null); jPanel1.add(label1, null); jPanel1.add(myPortField, null); jPanel1.add(label2, null); jPanel1.add(hostField, null); jPanel1.add(label3, null); jPanel1.add(portField, null); jPanel1.add(label4, null); jPanel1.add(inputField, null); jPanel1.add(label5, null); jPanel1.add(listenButton, null); jPanel1.add(connectButton, null); jPanel1.add(disconnectButton, null); jPanel1.add(quitButton, null); jPanel1.add(jScrollPane1, null); jScrollPane1.getViewport().add(outputField, null); } private String output_string = “”; public void receiveText(String s) { if (s == null) return; output_string = output_string + s; outputField.setText(output_string + “\n”); } static public void main(String [] args) { new ChatJFC(); } } GUI Programming Using Java C HAPTER 32 593 32 GUI PROGRAMMING U SING JAVA 3772316072 CH32 7/26/99 2:05 PM Page 593 The ChatJFC program is very similar to the ChatAWT program. I wrote the ChatJFC pro- gram by copying the ChatAWT program and doing the following: • Adding the import swing (JFC) package statement. • Changing Label to JLabel, Button to JButton, and so on. • Using the getContentPane method where required to get the internal container for adding components and setting the layout manager to null. Using Native Java Compilers There are two native mode Java compilers under development, one by TowerJ (www.towerj.com) and the other by Cygnus (www.cygnus.com). At the time this chapter was written (March 1999), the Cygnus compiler was available only in early test releases, but it looked promising. The TowerJ compiler is a commercial product. I have used it for three programs, and I have seen performance improvements from a factor of four to a factor of 11 over using a JIT (Just In Time compiler). One of the benefits of Java is the portability of its byte code. However, for server-side programs, giving up portability in favor of large performance improvements is often a good option. Summary This short chapter has hopefully given you both a quick introduction to the Java language and the motivation to study the language further. There are many sources of information for programming Java on the Internet. Because Web site links change, I will keep current links to my favorite Java resources on the Internet at my Web site (www.markwatson.com/books/linux_prog.html). Many interesting topics were not covered in this short chapter, such as: • Drawing graphics • Writing applets that run inside of Web browsers • More techniques for handling user interface events If you are primarily a C or C++ programmer, I urge you to also learn Java. I have been using C for 15 years and C++ for 10 years, but I prefer Java for most of my development work. Yes, it is true that Java programs will run slower than the equivalent C or C++ pro- grams. However, after using Java for about 3 years, I believe that Java enables me to write a large application in about half the time it takes to write the same application in C++. I have talked with other developers who agree that they are approximately twice as productive when programming in Java instead of C or C++. Programming the User Interface P ART IV 594 3772316072 CH32 7/26/99 2:05 PM Page 594 IN THIS CHAPTER • OpenGL is a Software Interface to Graphics Hardware 596 • The Orbits Sample Program 597 33 CHAPTER OpenGL/Mesa Graphics Programming by Mark Watson 3872316072 CH33 7/26/99 2:04 PM Page 595 The OpenGL API was developed at Silicon Graphics and has become an industry standard for high-quality 3D graphics. Although there are commercial ports of OpenGL to Linux, a high-quality public domain OpenGL-like implementation called Mesa has been written by Brian Paul. Mesa can not be called OpenGL because it is not licensed from Silicon Graphics, but I have found it to be an effective tool for OpenGL programming on Linux. Mesa might be included with your Linux distribution. Although I assume that you have installed and are using Mesa, I will refer to OpenGL in this chapter. I will keep a current link to the Mesa distribution on my web site. The OpenGL API is complex. We will use one simple example in this chapter to illustrate how to use the OpenGL auxiliary library to draw simple shapes, placing and rotating the shapes under program control. We will also learn how to use lighting effects and how to change the viewpoint. For most 3D graphics applications (like games), you need a sepa- rate modeling program to create 3D shapes, and you also need specialized code to use these shapes in OpenGL programs. The topics of modeling 3D images and using them in OpenGL programs is beyond the scope of this introductory chapter. Before reading this chapter, please download the latest Mesa distribution and install it in your home directory. The sample program for this chapter is located in the src/OpenGL directory on the CD-ROM. You will have to edit the first line of Makefile to reflect the path in your home directory where you have installed Mesa. The example program uses the OpenGL Utilities Library (GLUT). OpenGL itself is operating system- and device- independent. The GLUT library allows programmers to initialize OpenGL, create windows, and so on in a portable way. There are three example directories in the Mesa installation directory: book, demos, and samples. Please make sure that building Mesa also built exe- cutables for the many sample programs in these three directories. Then edit the first line of Makefile for the example program for this chapter and try running it to make sure that Mesa is set up properly on your computer. A few of the example programs in the Mesa distribution may not run with your graphics card; do not worry about this. OpenGL is a Software Interface to Graphics Hardware There are OpenGL software interface implementations for most 3D graphics cards, so OpenGL and Mesa will probably run efficiently on your computer unless you have a very old graphics card. Microsoft supports OpenGL on Windows 95, 98, and NT, so the pro- grams that you develop under Linux using Mesa will probably run with few modifica- tions under Windows. I worked at a computer animation company, Angel Studios Programming the User Interface P ART IV 596 3872316072 CH33 7/26/99 2:04 PM Page 596 (www.angel.com), where we used proprietary software for rendering real-time 3D graph- ics on a wide variety of hardware, including Nintendo Ultra-64, Windows, and SGI workstations. This proprietary software, as an option, used OpenGL to talk with graphics hardware. The Orbits Sample Program There are many features of OpenGL that we are not covering in the orbits example pro- gram for this chapter (for example, the use of display lists and texture mapping). The sample program in this section does illustrate several OpenGL programming techniques, but it is also simple enough for a tutorial example. The example program orbits.c is located in the src/OpenGL directory. The sample program uses the GLUT function glutSolidSphere to draw both a large “planet” and a small orbiting satellite. This example demonstrates the following: • Creating a window for OpenGL graphics and initializing OpenGL • Creating simple 3D objects using GLUT • Placing objects anywhere in a three-dimensional space using X-Y-Z coordinates • Rotating an object about any or all of the x-, y-, and z-axes. • Enabling the use of material properties so objects can be colored • Enabling depth tests so that rendered objects close to the viewer correctly cover objects that are obscured • Handling keyboard events • Updating OpenGL graphics for animation effects These operations are performed using both the OpenGL core API and the OpenGL utility library. All OpenGL implementations include the OpenGL utility library, so the simple example in this chapter should be easily portable to other operating systems and OpenGL implementations. OpenGL uses a modeling coordinate system where the X coordinate moves increasingly toward the right on the screen, the Y coordinate moves increasingly upward, and the z coordinate increases looking into the screen. The origin (for example, at X=Y=Z=0) is located at the center of the screen. The sample program cycles viewing angle, plus smooth or flat shading, when you hit any key (except for an escape, or q characters, that halt the program) while the program is running. OpenGL/Mesa Graphics Programming C HAPTER 33 597 33 OPENGL/MESA GRAPHICS PROGRAMMING 3872316072 CH33 7/26/99 2:04 PM Page 597 Figure 33.1 shows the orbits sample program running in the default smooth-shaded mode. The background color was changed to white for this figure; the program on the CD-ROM has a black background. Programming the User Interface P ART IV 598 FIGURE 33.1 The orbits pro- gram running with smooth- shading. Creating a Window for OpenGL Graphics and Initializing OpenGL In this chapter, we will use the following OpenGL utility library functions to initialize OpenGL, the GLUT library, and to create a window for drawing: Function Description glutInit Initializes GLUT and OpenGL. glutInitDisplayMode Sets display properties (our example program will set properties allowing for double buffering, depth queu- ing, and use of RGB colors). glutInitWindowSize Sets the size of the main window. glutInitWindowPosition Positions the main window on the desktop or X Windows display. glutCreateWindow Actually creates the main window. 3872316072 CH33 7/26/99 2:04 PM Page 598 The initialization code in the sample program looks like the following: glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(500, 500); glutInitWindowPosition(100, 100); glutCreateWindow(argv[0]); In calling glutInitDisplay, we use the following constants: Constant Description GLUT_DOUBLE Enables double buffering for smooth animation. GLUT_RGB Specifies the use of RGB color table. GLUT_DEPTH Enables the use of a depth buffer to determine when one object is obscuring another in a scene. Creating Simple 3D Objects Using GLUT There are several GLUT utility functions for creating both wire frame and solid objects. To create a sphere, use either of the following: void glutSolidSphere(GLdouble radius, GLint slices, GLint stacks); void glutWireSphere(GLdouble radius, GLint slices, GLint stacks); Here, radius is the radius of the sphere. The slices argument is the number of flat bands created around the z-axis. The higher the number of slices, the rounder the sphere. The stacks argument is the number of flat bands along the z-axis. The higher the slices value, the rounder the sphere. Lower slices and stacks values produce shapes that are drawn quicker. A sphere is drawn (or rendered) centered at the origin in modeling coordi- nates (for example, when the OpenGL Matrix mode is in modeling mode; more on this later). To create a cube, use either of the following: void glutSolidCube(GLdouble size); void glutWireCube(GLdouble size); The size argument is the length of any edge of the cube. To draw a cone, use either of the following: void glutSolidCone(GLdouble base, GLdouble height, GLint slices, GLint stacks); void glutWireCone(GLdouble base, GLdouble height, GLint slices, GLint stacks); OpenGL/Mesa Graphics Programming C HAPTER 33 599 33 OPENGL/MESA GRAPHICS PROGRAMMING 3872316072 CH33 7/26/99 2:04 PM Page 599 [...]... http://www.opengl.org/Documentation/Implementations/Mesa.html 3972316072 part5 7/26/99 2:30 PM Page 607 Special Programming Techniques PART V IN THIS PART • Shell Programming with GNU bash • Secure Programming 639 • Debugging: GNU gdb 687 609 3972316072 part5 7/26/99 2:30 PM Page 6 08 CHAPTER 34 4072316072 CH34 7/26/99 2: 28 PM Page 609 Shell Programming with GNU bash by Kurt Wall IN THIS CHAPTER • Why bash? 610 • bash Basics... Functions 615 619 6 28 • Input and Output 629 • Command-line Processing 633 • Processes and Job Control 635 4072316072 CH34 7/26/99 2: 28 PM Page 610 610 Special Programming Techniques PART V Within the first two days of becoming a Linux user in 1993, I wrote my first bash script, a very kludgy effort to automate my backups This anecdote illustrates how pervasive shell scripting is in Linux In this chapter,... orbiting satellite } glPopMatrix(); 33 OPENGL/MESA GRAPHICS PROGRAMMING // push matrix, draw central planet, then pop matrix: glPushMatrix(); { glRotatef((GLfloat)planet_rotation_period, 0.0, 1.0, 0.0); glColor4f(1.0, 0.0, 0.0, 1.0); glutSolidSphere(1.0, 10, 8) ; // Draw the central planet } glPopMatrix(); 387 2316072 CH33 7/26/99 2:04 PM Page 602 602 Programming the User Interface PART IV Initially, we call... an example Although it can be quite long, the individual directories are colon-delimited Table 34.3 lists bash’s pattern-matching operators and their function 4072316072 CH34 7/26/99 2: 28 PM Page 6 18 6 18 Special Programming Techniques PART V NOTE The dirname command strips the non-directory suffix from a filename passed to it as an argument and prints the result to standard output Conversely, basename... glTranslatef(10.0, 0.0, 1.0); // translate the model // coordinate system glutSolidSphere(1.0, 40, 40); // Draw a very detailed sphere } glPopMatrix(); 387 2316072 CH33 7/26/99 2:04 PM Page 601 OpenGL/Mesa Graphics Programming CHAPTER 33 601 As a matter of programming style, I enclose within curly braces any operations between the “push” and the “pop”; this improves the readability of the code In this example,... called by the GLUT library whenever the window needs to be redrawn The function signature for display is: void display(void) 33 OPENGL/MESA GRAPHICS PROGRAMMING glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); 387 2316072 CH33 7/26/99 2:04 PM Page 604 604 Programming the User Interface PART IV We register this Callback function in main by calling: glutDisplayFunc(display); The last thing that display... customizability and the complete programming environment it provides, including function definitions, integer math, and a surprisingly complete I/O interface As you might expect of a Linux utility, bash contains elements of all of the popular shells, Bourne, Korn, and C shell, as well as a few innovations of its own As of this writing, the current release of bash is 2.0.3 Most Linux distributions, however,... obtain the same output: $ echo c{a{r,t,n},on}s 34 SHELL PROGRAMMING WITH GNU BASH The following examples illustrate using the set notation and also how you can use the wildcard operators with sets To list all of the files in the directory above whose second letter is a vowel, you could write: 611 4072316072 CH34 7/26/99 2: 28 PM Page 612 612 Special Programming Techniques PART V Special Characters The... has special facilities for dealing with numeric (integer) values, too To assign a value to a variable, use the following syntax: 4072316072 CH34 7/26/99 2: 28 PM Page 614 614 Special Programming Techniques PART V The strong quotes on lines 7 and 8 prevent bash from expanding the variables As you can see in the script’s output below, $MYNAME_ is empty and prints nothing, but ${MYNAME}_ produces the expected... illustrates the differences between “$#” and “$@” Listing 34.2 1 2 3 4 5 6 7 8 9 POSITIONAL PARAMETERS #!/bin/bash # Listing 34.2 # posparm.sh - Using positional parameters ########################################## function cntparm { echo -e “inside cntparm $# parms: $*\n” } 4072316072 CH34 7/26/99 2: 28 PM Page 615 Shell Programming with GNU bash CHAPTER 34 10 11 12 13 14 15 615 cntparm “$*” cntparm . 1 68) ; this.getContentPane().setLayout(null); quitButton.setBounds(4 48, 280 , 121, 32); GUI Programming Using Java C HAPTER 32 591 32 GUI PROGRAMMING U SING JAVA continues 3772316072 CH32 7/26/99 2:05. at: http://www.opengl.org/Documentation/Implementations/Mesa.html Programming the User Interface P ART IV 606 Listing 33.1 CONTINUED 387 2316072 CH33 7/26/99 2:04 PM Page 606 Special Programming Techniques PART V IN THIS PART • Shell Programming. Silicon Graphics, but I have found it to be an effective tool for OpenGL programming on Linux. Mesa might be included with your Linux distribution. Although I assume that you have installed and are

Ngày đăng: 12/08/2014, 21:20

Từ khóa liên quan

Mục lục

  • Part IV Programming the User Interface

    • Ch 33 OpenGL/Mesa Graphics Programming

    • Part V Special Programming Techniques

      • Ch 34 Shell Programming with GNU bash

      • Ch 35 Secure Programming

Tài liệu cùng người dùng

Tài liệu liên quan