在Java的GUI编程中,如何在矩形中显示字符串?
以下示例演示如何使用drawRect()
方法在每个字符周围绘制一个矩形来显示矩形中的每个字符。
package com.yiibai;
import java.awt.*;
import javax.swing.*;
public class DisplayTextInRectangle extends JPanel {
public void paint(Graphics g) {
g.setFont(new Font("", 0, 50));
FontMetrics fm = getFontMetrics(new Font("", 0, 50));
String s = "Max vs. Min";
int x = 5;
int y = 5;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
int h = fm.getHeight();
int w = fm.charWidth(c);
g.drawRect(x, y, w, h);
g.drawString(String.valueOf(c), x, y + h);
x = x + w;
}
}
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new DisplayTextInRectangle());
frame.setSize(500, 700);
frame.setVisible(true);
}
}
上述代码示例将产生以下结果。
示例-2
以下是在矩形中显示字符串的另一个示例。
package com.yiibai;
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
class MyCanvas extends JComponent {
String s = "This is a message.";
int x = 45;
int y = 45;
public void paint(Graphics g) {
g.drawRect (10, 10, 200, 200);
g.setColor(Color.blue);
g.drawString(s, x, y);
}
}
public class DisplayTextInRectangle2 {
public static void main(String[] a) {
JFrame window = new JFrame();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setBounds(30, 30, 300, 300);
window.getContentPane().add(new MyCanvas());
window.setVisible(true);
}
}
上述代码示例将产生以下结果。