Disegnare il Testo

 

 

 

Oggetto: Disegnate testo mediante grafica 2D

 

Contenuti:

1

Docs.oracle.com tutorial Grafica2d

2

 

3  
4  

 

Esempi:

1

 

2  
3  
4  

 

 1 package helloworldtext;
 2 
 3 import javax.swing.*;
 4 import java.awt.*;
 5 import java.awt.geom.Line2D;
 6 
 7 public class HelloWorldText  extends JFrame {
 8 
 9     public HelloWorldText () {
10         setTitle("Hello World");
11         setSize(250, 200);
12         setLocationRelativeTo(null); // Centra la finestra sullo schermo
13         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
14         setVisible(true);
15     }
16 
17     @Override
18     public void paint(Graphics g) {
19         super.paint(g);
20 
21         Graphics2D g2d = (Graphics2D) g;
22 
23         // Disegna la linea rossa
24         g2d.setColor(Color.RED);
25         g2d.draw(new Line2D.Double(0, 80, 250, 80)); // Linea superiore
26 
27         // Calcola la posizione della linea sotto
28         int textHeight = 90; // Altezza della scritta "Hello World"
29         int lineDistance = 2; // Distanza tra la scritta e le linee
30         int lineaSottoY = textHeight + lineDistance; // Posizione della linea sotto
31 
32         // Disegna la linea sotto
33       
34         g2d.draw(new Line2D.Double(0, lineaSottoY, 250, lineaSottoY)); // Linea inferiore
35 
36         // Disegna il testo "Hello World"
37         g2d.setColor(Color.BLACK);
38         g2d.setFont(new Font("Arial", Font.PLAIN, 12));
39         g2d.drawString("Hello World", 95, textHeight);
40     }
41 
42     public static void main(String[] args) {
43         SwingUtilities.invokeLater(() -> new HelloWorldText());
44     }
45 }