Java 示例 - 使用 GUI 绘制文本
-
问题描述
如何使用 GUI 绘制文本? -
解决方案
下面的例子演示了如何绘制文本,Graphics 类的 drawString()、setFont() 方法。import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel{ public void paint(Graphics g) { Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Serif", Font.PLAIN, 96); g2.setFont(font); g2.drawString("Text", 40, 120); } public static void main(String[] args) { JFrame f = new JFrame(); f.getContentPane().add(new Main()); f.setSize(300, 200); f.setVisible(true); } }
-
结果
上面的代码示例将产生以下结果。Text is displayed in a frame.
以下是使用 GUI 绘制文本的示例。import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import javax.swing.JFrame; import javax.swing.JPanel; public class Panel extends JPanel { public void paint(Graphics gr) { Graphics2D g = (Graphics2D)gr; g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Font font = new Font("Serif", Font.PLAIN, 96); g.setFont(font); g.drawString("Tutorialspoint", 40, 120); } public static void main(String[] args) { JFrame f = new JFrame(); f.getContentPane().add(new Panel()); f.setSize(300, 200); f.setVisible(true); } }
-
结果
上面的代码示例将产生以下结果。Text is displayed in a frame.