logo
down
shadow

How can I center Graphics.drawString() in Java?


How can I center Graphics.drawString() in Java?

By : user2953184
Date : November 20 2020, 01:01 AM
Any of those help I used the answer on this question.
The code I used looks something like this:
code :
/**
 * Draw a String centered in the middle of a Rectangle.
 *
 * @param g The Graphics instance.
 * @param text The String to draw.
 * @param rect The Rectangle to center the text in.
 */
public void drawCenteredString(Graphics g, String text, Rectangle rect, Font font) {
    // Get the FontMetrics
    FontMetrics metrics = g.getFontMetrics(font);
    // Determine the X coordinate for the text
    int x = rect.x + (rect.width - metrics.stringWidth(text)) / 2;
    // Determine the Y coordinate for the text (note we add the ascent, as in java 2d 0 is top of the screen)
    int y = rect.y + ((rect.height - metrics.getHeight()) / 2) + metrics.getAscent();
    // Set the font
    g.setFont(font);
    // Draw the String
    g.drawString(text, x, y);
}


Share : facebook icon twitter icon
Center text output from Graphics.DrawString()

Center text output from Graphics.DrawString()


By : Sergio Rudenko
Date : March 29 2020, 07:55 AM
should help you out I'm using the .NETCF (Windows Mobile) Graphics class and the DrawString() method to render a single character to the screen. , Through a combination of the suggestions I got, I came up with this:
code :
    private void DrawLetter()
    {
        Graphics g = this.CreateGraphics();

        float width = ((float)this.ClientRectangle.Width);
        float height = ((float)this.ClientRectangle.Width);

        float emSize = height;

        Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);

        font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);

        SizeF size = g.MeasureString(letter.ToString(), font);
        g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);

    }

    private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)
    {
        // Compute actual size, shrink if needed
        while (true)
        {
            SizeF size = g.MeasureString(text, font);

            // It fits, back out
            if (size.Height <= proposedSize.Height &&
                 size.Width <= proposedSize.Width) { return font; }

            // Try a smaller font (90% of old size)
            Font oldFont = font;
            font = new Font(font.Name, (float)(font.Size * .9), font.Style);
            oldFont.Dispose();
        }
    }
Java Graphics.drawString doesn't always work

Java Graphics.drawString doesn't always work


By : Darren
Date : March 29 2020, 07:55 AM
wish of those help Has anyone ever run into this issue before? Sometimes the string displays, sometimes half of it, sometimes none of it. The issue is worsened when using VolatileImage instead of BufferedImage as a backbuffer. , The code needed to be ran in the SWING thread!
Graphics.DrawString center in printdocument width

Graphics.DrawString center in printdocument width


By : Jepysn
Date : March 29 2020, 07:55 AM
may help you . The following works for me. You may need to use PageBounds if your margins are not uniform.
code :
    void pd_PrintPage(object sender, PrintPageEventArgs e)
    {
        int w = e.MarginBounds.Width / 2;
        int x = e.MarginBounds.Left;
        int y = e.MarginBounds.Top;
        Font printFont = new Font("Arial", 10);
        Bitmap logo = System.Drawing.SystemIcons.WinLogo.ToBitmap();

        int height = 100 + y;
        string tabDataText = "Hello World";
        var tabDataForeColor = Color.Blue;
        var txtDataWidth = e.Graphics.MeasureString(tabDataText, printFont).Width;

        e.Graphics.DrawImage(logo,
            e.MarginBounds.Left + (e.MarginBounds.Width / 2) - (logo.Width / 2),
            e.MarginBounds.Top + (e.MarginBounds.Height / 2) - (logo.Height));

        using (var sf = new StringFormat())
        {
            height += logo.Height + 15;
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Center;
            e.Graphics.DrawString(tabDataText, new Font(this.Font.Name, 10),
                 new SolidBrush(tabDataForeColor),
                 e.MarginBounds.Left + (e.MarginBounds.Width / 2),
                 e.MarginBounds.Top + (e.MarginBounds.Height / 2) + (logo.Height / 2) + 15,
                 sf);
        }

        e.HasMorePages = false;
    }
Java Graphics g.drawString

Java Graphics g.drawString


By : Karen
Date : March 29 2020, 07:55 AM
help you fix your problem Here I have two methods, one which generates a list based on instances and the other which uses drawString() to display some text... , use the following code:
code :
public class MyClass extends JComponent {
    HashMap<String, Color> map = new HashMap<>();
    private static final String BOY = "B";
    private static final String GIRL = "G";

    public MyClass() {
        String[] peopleArray = new String[people.size()];
        map.put(BOY, Color.RED);
        map.put(GIRL, Color.GREEN);
        for (int i = 0; i < people.size(); i++) {
            if (people.get(i) instanceof Boy) {
            peopleArray[i] = BOY;
            System.out.print(BOY);
        } else if (people.get(i) instanceof Girl) {
            peopleArray[i] = GIRL;
            System.out.print(GIRL);
        }
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        //you might need a for-loop or smth here. I'll just draw a boy in this example.
        g.setColor(map.get(BOY));
        int x = 10;
        int y = 10;
        g.drawString(BOY, x, y);
    }
}
java - why does graphics.drawString() not redraw?

java - why does graphics.drawString() not redraw?


By : user3799701
Date : March 29 2020, 07:55 AM
To fix this issue this is beyond me (be forgiving, it's late). I'm subclassing a WindowsSliderUI, because I want it to draw a bigger thumb (is that the right word?)(that's working) and also display the value of the slider just above it (like, for example, gtk look and feel does)(that's broken). I'm overriding the paint() method, and at the moment it looks like this: (it's long, my changes are near the bottom): , I don't know the complete answer, but your call to
Related Posts Related Posts :
  • Forcefully terminating a thread I didn't write in Java
  • Issue with ojdbc jar in Maven
  • String array length java
  • Java basic compilation error
  • Inquiry about writing a Char via ByteBuffer
  • Getting unexpected results when type casting between long and double
  • Variable throws variable might not have been initialized error
  • Start/stop java application from an external script
  • Confusion in declaring String Objects
  • What are some ways to do multi-core programming on Android, not just multi-thread?
  • hibernate - process scoped identity
  • Null Pointer Exception on getGraphics()
  • Can we print a java message on console without using main method, static variable and static method?
  • sending text from editText to ListView (2 activities)
  • Transfer value from JList to another class in Java
  • Creating 2 streams with one socket
  • How measure time stolen from virtual machine, in Scala/Java?
  • How can I programmatically generate keypress events?
  • org.apache.commons.net.ssh documentation
  • Implementation of Dijkstra`s Algorithm - Stuck in an infinite loop
  • Should I throw IllegalArgmentException when 'user of given id not exist'?
  • In Nimbus, how to paint TextField when MouseOver?
  • why won't checkforWin(File f) return true when it is true?
  • Android: Cursor is always returning null even if the database is not empty
  • Repeating for loop in menu
  • Can Java garbage collector randomly delete objects in the On-Heap tier?
  • Apache CXF Exception: SSL connection unexpectedly closed
  • Add properties to ArrayList<Object> in Java
  • Multiple Adapters or One Adapter for different lists and objects - Code Performance
  • Is it good practice in Java for a class's method to redundantly return a modified global field of the class?
  • How to change the color of the background in libgdx labels?
  • direct file path not working
  • ClassFileTransformer + Javassist: no such field
  • How do I change and instance variable for an object which the user selects from a combobox?
  • reading and updating a large xml file in java
  • ActionListener and Thread.sleep
  • What is the maximum of number of arguments for varargs in java?
  • When I compile I get an error as "ask" cannot be resolved or is not a field"
  • What is the best way to check if 4 integer variables are equal to 0?
  • Storing constant webdriver elements in an enum
  • Java: Why main class does not extend Thread class
  • Java - how to find out if a directory is being used by another process?
  • How can I get a method to print?
  • Java unknown exceptions
  • BufferedReader,StreamWriter crash
  • found raw type: JComboBox
  • Java Generics -> Function return type
  • how to refresh contents of jtable on event of action listener?
  • Why does List interface extend Collection interface?
  • Pros and Cons of Clojure http client libraries
  • use final inside a for each loop
  • Convert java data object to service object
  • Unsupported major.minor version 51.0 while executing JSP
  • How do I display a word diagonally in Java?
  • making sure one task completes before another starts in java
  • My program gives an index out of bounds error
  • Removing duplicate characters in a String (user inputted keyword)
  • Jersey 2.0 Content-Length not set
  • AWS.SimpleQueueService.NonExistentQueue Exception thrown when Accessing Existing SQS queue
  • Where can I find the source code for the com.sun.jdi package?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org