Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Intro_Java_brief_Liang2011.pdf
Скачиваний:
113
Добавлен:
26.03.2016
Размер:
10.44 Mб
Скачать

624 Chapter 18 Applets and Multimedia

59frame.setLocationRelativeTo(null); // Center the frame

60frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

61frame.setVisible(true);

62}

63

64/** Get command-line parameters */

65private void getCommandLineParameters(String[] args) {

66// Check usage and get x, y and message

67if (args.length != 3) {

68System.out.println(

69"Usage: java DisplayMessageApp x y message");

70System.exit(0);

71}

72else {

73x = Integer.parseInt(args[0]);

74y = Integer.parseInt(args[1]);

75message = args[2];

76}

77}

78}

When you run the program as an applet, the main method is ignored. When you run it as an application, the main method is invoked. Sample runs of the program as an application and as an applet are shown in Figure 18.8.

FIGURE 18.8 The DisplayMessageApp class can run as an application and as an applet.

The main method creates a JFrame object frame and creates a JApplet object applet, then places the applet applet into the frame frame and invokes its init method. The application runs just like an applet.

The main method sets isStandalone true (line 45) so that it does not attempt to

 

retrieve HTML parameters when the init method is invoked.

 

The setVisible(true) method (line 61) is invoked after the components are added to

 

the applet, and the applet is added to the frame to ensure that the components will be visible.

 

Otherwise, the components are not shown when the frame starts.

 

Important Pedagogical Note

omitting main method

From now on, all the GUI examples will be created as applets with a main method. Thus you will

 

be able to run the program either as an applet or as an application. For brevity, the main method

 

is not listed in the text.

18.8 Case Study: Bouncing Ball

This section presents an applet that displays a ball bouncing in a panel. Use two buttons to suspend and resume the movement, and use a scroll bar to control the bouncing speed, as shown in Figure 18.9.

Here are the major steps to complete this example:

1.Create a subclass of JPanel named Ball to display a ball bouncing, as shown in Listing 18.7.

18.8 Case Study: Bouncing Ball 625

FIGURE 18.9 The ball’s movement is controlled by the Suspend and Resume buttons and the scroll bar.

2.Create a subclass of JPanel named BallControl to contain the ball with a scroll bar and two control buttons Suspend and Resume, as shown in Listing 18.8.

3.Create an applet named BounceBallApp to contain an instance of BallControl and enable the applet to run standalone, as shown in Listing 18.9.

The relationship among these classes is shown in Figure 18.10.

javax.swing.JPanel

 

 

javax.swing.JPanel

 

 

javax.swing.JApplet

 

 

1

1

 

 

1

1

 

 

 

 

 

 

Ball

 

BallControl

BounceBallApp

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

-x: int

 

 

-ball: Ball

 

 

+BounceBallApp()

-y: int

 

 

-jsbDelay: JScrollBar

 

 

+main(args: String[]): void

-dx: int

 

 

-jbtResume: JButton

 

 

 

-dy: int

 

 

-jbtSuspend: JButton

 

 

 

-radius: int

-delay: int

+BallControl()

 

-timer: Timer

 

 

 

+Ball()

 

+suspend(): void

 

+resume(): void

 

+setDelay(delay: int): void

 

FIGURE 18.10 BounceBallApp contains BallControl, and BallControl contains Ball.

LISTING 18.7 Ball.java

1 import javax.swing.Timer;

2 import java.awt.*;

3 import javax.swing.*;

4 import java.awt.event.*;

5

6 public class Ball extends JPanel {

7 private int delay = 10;

8

9// Create a timer with delay 1000 ms

10 private Timer timer = new Timer(delay, new TimerListener());

11

12private int x = 0; private int y = 0; // Current ball position

13private int radius = 5; // Ball radius

14private int dx = 2; // Increment on ball's x-coordinate

15private int dy = 2; // Increment on ball's y-coordinate

16

timer delay

create timer

626 Chapter 18

Applets and Multimedia

 

17

 

public Ball() {

start timer

18

 

 

timer.start();

 

 

19

}

 

 

 

 

 

 

 

20

 

 

 

 

 

 

 

 

timer listener

21

 

private class TimerListener implements ActionListener {

 

 

22

 

 

/** Handle the action event */

 

23

 

 

public void actionPerformed(ActionEvent e) {

repaint ball

24

 

 

 

repaint();

 

 

 

 

25

}

 

 

 

 

 

 

26

}

 

 

 

 

 

 

 

27

 

 

 

 

 

 

 

 

paint ball

28

 

protected void paintComponent(Graphics g) {

 

 

 

 

super.paintComponent(g);

 

29

 

 

 

30

 

 

 

 

 

 

 

 

 

31

 

 

g.setColor(Color.red);

 

32

 

 

 

 

 

 

 

 

 

33

 

 

// Check boundaries

 

34

 

 

if (x < radius) dx = Math.abs(dx);

 

35

 

 

if (x > getWidth() - radius) dx = -Math.abs(dx);

 

36

 

 

if (y < radius) dy = Math.abs(dy);

 

37

 

 

if (y > getHeight() - radius) dy = -Math.abs(dy);

 

38

 

 

 

 

 

 

 

 

 

39

 

 

// Adjust ball position

 

40

 

 

x += dx;

 

41

 

 

y += dy;

 

42

 

 

g.fillOval(x - radius, y - radius, radius * 2, radius * 2);

 

43

}

 

 

 

 

 

 

 

44

 

 

 

 

 

 

 

 

 

45

public void suspend() {

 

46

 

timer.stop(); // Suspend timer

 

47

}

 

 

 

 

 

 

 

48

 

 

 

 

 

 

 

 

 

49

public void resume() {

 

50

 

timer.start(); // Resume timer

 

51

}

 

 

 

 

 

 

 

52

 

 

 

 

 

 

 

 

53public void setDelay(int delay) {

54this.delay = delay;

55timer.setDelay(delay);

56}

57}

The use of Timer to control animation was introduced in §16.12, “Animation Using the Timer Class.” Ball extends JPanel to display a moving ball. The timer listener implements ActionListener to listen for ActionEvent (line 21). Line 10 creates a Timer for a Ball. The timer is started in line 18 when a Ball is constructed. The timer fires an ActionEvent at a fixed rate. The listener responds in line 24 to repaint the ball to animate ball movement. The center of the ball is at (x, y), which changes to (x + dx, y + dy) on the next display (lines 40–41). The suspend and resume methods (lines 45–51) can be used to stop and start the timer. The setDelay(int) method (lines 53–56) sets a new delay.

LISTING 18.8 BallControl.java

 

1

import javax.swing.*;

 

2

import java.awt.event.*;

 

3

import java.awt.*;

 

4

 

 

5

public class BallControl extends JPanel {

button

6

private Ball ball = new Ball();

18.8 Case Study: Bouncing Ball 627

7private JButton jbtSuspend = new JButton("Suspend");

8

private JButton jbtResume =

new JButton("Resume");

scroll bar

9

private JScrollBar jsbDelay

= new JScrollBar();

 

 

10

 

 

 

 

11

public BallControl() {

 

 

create UI

12// Group buttons in a panel

13JPanel panel = new JPanel();

14panel.add(jbtSuspend);

15panel.add(jbtResume);

16

17// Add ball and buttons to the panel

18ball.setBorder(new javax.swing.border.LineBorder(Color.red));

19jsbDelay.setOrientation(JScrollBar.HORIZONTAL);

20ball.setDelay(jsbDelay.getMaximum());

21setLayout(new BorderLayout());

22add(jsbDelay, BorderLayout.NORTH);

23add(ball, BorderLayout.CENTER);

24add(panel, BorderLayout.SOUTH);

25

 

 

 

 

26

// Register listeners

 

27

jbtSuspend.addActionListener(new ActionListener() {

register listener

28

public void actionPerformed(ActionEvent e) {

 

29

 

ball.suspend();

 

suspend

30}

31});

32

jbtResume.addActionListener(new ActionListener() {

register listener

33

public void actionPerformed(ActionEvent e) {

 

34

 

ball.resume();

 

resume

35}

36});

37

jsbDelay.addAdjustmentListener(new AdjustmentListener() {

register listener

38

public void adjustmentValueChanged(AdjustmentEvent e) {

 

39

 

ball.setDelay(jsbDelay.getMaximum() - e.getValue());

 

new delay

40}

41});

42}

43}

The BallControl class extends JPanel to display the ball with a scroll bar and two control buttons. When the Suspend button is clicked, the ball’s suspend() method is invoked to suspend the ball movement (line 29). When the Resume button is clicked, the ball’s resume() method is invoked to resume the ball movement (line 34). The bouncing speed can be changed using the scroll bar.

LISTING 18.9 BounceBallApp.java

1 import java.awt.*;

2 import javax.swing.*;

3

4 public class BounceBallApp extends JApplet {

5 public BounceBallApp() {

6add(new BallControl());

7

}

8

}

add BallControl

main method omitted

The BounceBallApp class simply places an instance of BallControl in the applet. The main method is provided in the applet (not displayed in the listing for brevity) so that you can also run it standalone.

Тут вы можете оставить комментарий к выбранному абзацу или сообщить об ошибке.

Оставленные комментарии видны всем.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]