19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

494 Chapter 13 Graphics<br />

This method returns the font metrics of the current font.<br />

You can use the following instance methods in the FontMetrics class <strong>to</strong> obtain the attributes<br />

of a font and the width of a string when it is drawn using the font:<br />

public int getAscent() // Return the ascent<br />

public int getDescent() // Return the descent<br />

public int getLeading() // Return the leading<br />

public int getHeight() // Return the height<br />

public int stringWidth(String str) // Return the width of the string<br />

Listing 13.6 gives an example that displays a message in the center of the panel, as shown in<br />

Figure 13.17.<br />

create a message panel<br />

add a message panel<br />

set background<br />

set font<br />

override paintComponent<br />

get FontMetrics<br />

LISTING 13.6<br />

TestCenterMessage.java<br />

1 import javax.swing.*;<br />

2 import java.awt.*;<br />

3<br />

4 public class TestCenterMessage extends JFrame {<br />

5 public TestCenterMessage() {<br />

6 CenterMessage messagePanel = new CenterMessage();<br />

7 add(messagePanel);<br />

8 messagePanel.setBackground(Color.WHITE);<br />

9 messagePanel.setFont(new Font("Californian FB", Font.BOLD, 30));<br />

10 }<br />

11<br />

12 /** Main method */<br />

13 public static void main(String[] args) {<br />

14 TestCenterMessage frame = new TestCenterMessage();<br />

15 frame.setSize(300, 150);<br />

16 frame.setTitle("CenterMessage");<br />

17 frame.setLocationRelativeTo(null); // Center the frame<br />

18 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br />

19 frame.setVisible(true);<br />

20 }<br />

21 }<br />

22<br />

23 class CenterMessage extends JPanel {<br />

24 @Override /** Paint the message */<br />

25 protected void paintComponent(Graphics g) {<br />

26 super.paintComponent(g);<br />

27<br />

28 // Get font metrics for the current font<br />

29 FontMetrics fm = g.getFontMetrics();<br />

30<br />

31 // Find the center location <strong>to</strong> display<br />

32 int stringWidth = fm.stringWidth("Wel<strong>com</strong>e <strong>to</strong> <strong>Java</strong>") ;<br />

33 int stringAscent = fm.getAscent() ;<br />

34<br />

35 // Get the position of the leftmost character in the baseline<br />

36 int xCoordinate = getWidth() / 2 - stringWidth / 2;<br />

37 int yCoordinate = getHeight() / 2 + stringAscent / 2;<br />

38<br />

39 g.drawString("Wel<strong>com</strong>e <strong>to</strong> <strong>Java</strong>", xCoordinate, yCoordinate);<br />

40 }<br />

41 }

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!