Home > Net >  Displaying code inside rectangle in Java GUI
Displaying code inside rectangle in Java GUI

Time:04-11

// 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
            int x = 100;
            int y = 100;
     
     
            g.drawRect(100,100,200,200);
            g.setColor(Color.RED);
            g.drawString(insideRect, x,y);
            
        }
        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][1] [1]: https://i.stack.imgur.com/daWM5.jpg

CodePudding user response:

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;

CodePudding user response:

I would suggest that you start by looking at 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...

  • Related