1
// Eine einfache grafische Benutzeroberfläche mit Swing
    //von der Zeile 3 bis zur Zeile 5; Impotieren von Bibliothek
    import java.awt.*;
    import javax.swing.*;
    import java.awt.Graphics;
     
     
    public class HelloGUI extends JFrame { //  public class HelloGui
        public HelloGUI (String title) {
        super(title);
            getContentPane().add("North",new JButton("Hello World"));
            setSize(400,400);
            setVisible(true);
        setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
        
        }
     
        
        public void paint (Graphics g) {
     
            /* Das Verwenden von pain Methode
            * Graphics ist ein Parameter 
            * in g ist das Parameter Graphics gespeichert 
            */
            String insideRect = "Hello World!";
            //this String should be displayed inside of the rectangel
        
            
        }
        public static void main(String args[]) {
            new HelloGUI("Hello World ");
        }
    }

0 Antworten

I want to write a simpl java gui App, which display the Strin "Hello world", but it is very important to me that "Hello world" must be inside a rectangle. so used the method g.drawRect() to draw a rectangle and the method g.drawString() to display the String "Hello World!" or any other message. The Code work , but Hello World is not displayed iside the reactangle. Can anybody help me to display the string "Hello Wolrd!"inside the rectangle... I try it but it didn't work. that is my code! tnx so here is a screenshot of my result

enter image description here

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
Babo khan
  • 23
  • 4
  • Please show a screenshot of your app. – Code-Apprentice Apr 10 '22 at 20:48
  • 2
    Read [the documentation of Graphics.drawString](https://docs.oracle.com/en/java/javase/18/docs/api/java.desktop/java/awt/Graphics.html#drawString(java.lang.String,int,int)) carefully. The second sentence says: “The baseline of the leftmost character is at position (x, y) in this graphics context's coordinate system.” – VGR Apr 10 '22 at 20:48
  • @Code-Apprentice hey tnx for respounding !! i did it !! – Babo khan Apr 10 '22 at 21:05

2 Answers2

4

I would suggest that you start by looking at Working with Text APIs

When drawing text, text is drawn from the base line UP (that is, the y position represents the baseline and the (majority) of the text is drawn above it)

enter image description here

* From Measuring Text

In order to draw text so that it appears to be drawn "below" the y position, you need to offset the y position by the ascent height of the font.

For example...

FontMetrics fm = g2d.getFontMetrics();
g2d.drawRect(100, 100, 200, 200);
g2d.setColor(Color.RED);
g2d.drawString(insideRect, x, y + fm.getAscent());

But why not use Font#getSize?

Font#getSize "Returns the point size of this Font" (from the JavaDocs), the physical requirements of the font may differ based on the rendering workflow and is not a "true" measure of the physical height (or rendering properties) of the font.

You should also take a closer look at Painting in AWT and Swing and Performing Custom Painting to get a better idea of how painting works in Swing and how you should be working with it, as you're going to end up with no end of issues with your current approach.

Runnable example

import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main {
    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            String insideRect = "Hello World!";
            //this String should be displayed inside of the rectangel
            int x = 100;
            int y = 100;

            FontMetrics fm = g2d.getFontMetrics();
            g2d.drawRect(100, 100, 200, 200);
            g2d.setColor(Color.RED);
            g2d.drawString(insideRect, x, y + fm.getAscent());
            g2d.dispose();
        }

    }
}

If you want to centre the text (horizontally and vertically) you need to understand the difference between "absolute" or "baseline" centring (on the vertical axis), that is, are you trying to centre the text based on its baseline or its overall height? There is a subtle difference between the two

For example...

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

Your String is actually inside the rectangle, in the upper left corner. However it doesn't take the font size into consideration. The code below should put the text within the borders of the rectangle:

    public void paint (Graphics g) {
 
        /* Das Verwenden von pain Methode
        * Graphics ist ein Parameter 
        * in g ist das Parameter Graphics gespeichert 
        */
        String insideRect = "Hello World!";
        //this String should be displayed inside of the rectangel
        int x = 100;
        int y = 100;
        g.drawRect(100,100,200,200);
        g.setColor(Color.RED);

        // add an offset to y coordinate
        Font font = g.getFont();
        g.drawString(insideRect, x ,y + font.getSize());
    }

Edit: To center the text you should play with the height and width of you rectangle & text, changing the texts x and y coordinates. Below I created widthOffset and heightOffset based on the width/height of the rectangle & text:

    public void paint (Graphics g) {
 
        /* Das Verwenden von pain Methode
        * Graphics ist ein Parameter 
        * in g ist das Parameter Graphics gespeichert 
        */
        String insideRect = "Hello World!";
        //this String should be displayed inside of the rectangel
        int x = 100;
        int y = 100;
        g.drawRect(100,100,200,200);
        g.setColor(Color.RED);

        // center the text inside the rectangle
        Font font = g.getFont();
        FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
        Rectangle2D textRectangle = font.getStringBounds(insideRect, frc);
        int textWidth = (int) textRectangle.getWidth();
        int textHeight = (int) textRectangle.getHeight();

        int widthOffset = 100 - textWidth/2; // 100 = rectangle width / 2
        int heightOffset = 100 + textHeight/2; // 100 = rectangle height / 2

        g.drawString(insideRect, x + widthOffset ,y + heightOffset);
    }

To run the snippet above you should also import:

import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
happy songs
  • 835
  • 8
  • 21
  • I am greatfull to you !! It really works. @happy songs I have still one question : Do you know how I put the text in the center of ther Reactangle ? – Babo khan Apr 10 '22 at 21:30
  • I edited the answer, check the code below **Edit**. To center the text you should play with `x` and `y` coordinates of your text inside the rectangle container. – happy songs Apr 10 '22 at 22:10
  • Tnx a lot !! I really appreciate you !! @happy songs – Babo khan Apr 10 '22 at 22:22
  • Could you please explain why we use super(title) – Babo khan Apr 11 '22 at 21:53
  • Font.getSize is wrong. FontMetrics.getAscent is right. The font size is the total line height in points, not pixels. A 10 point font has lines which are ¹⁰⁄₇₂ inches high; how many pixels that requires depends on the screen’s dot pitch. – VGR Apr 17 '22 at 00:16