Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

how to drawString() at the center of jpanel?

838975Jun 18 2011 — edited Jun 20 2011
the number 8 doent be placed on center of image but near to the top left
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;

public class Test
{   public static void main(String[] args)
    {	SwingUtilities.invokeLater(new Runnable() {
            public void run()
	    {	new Test();
            }
        });
    }

    JFrame frame;

    Test()
    {	System.out.println("Created GUI on EDT? " + SwingUtilities.isEventDispatchThread());
	frame = new JFrame();

        frame.setContentPane(new TestWord());

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        //.requestFocusInWindow();

        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}

class TestWord extends JPanel
{   int w = 150, h = 150;
    int scale = 1;

    BufferedImage bimg = new BufferedImage(w*scale, h*scale, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = bimg.createGraphics();

    TestWord()
    {	this.setPreferredSize(new Dimension(w*scale, h*scale));
	this.setBackground(new Color(125,125,125));

	g.setColor(Color.white);
	g.fillRect(0, 0, w*scale, h*scale);

	g.setColor(Color.red);
	g.drawLine(0, h*scale/2, w*scale, h*scale/2);
	g.drawLine(w*scale/2, 0, w*scale/2, h*scale);
	g.drawLine(0, 0, w*scale, w*scale);
	g.drawLine(w*scale, 0, 0, w*scale);

	g.setFont(new Font("Arial", Font.BOLD, 120));
	FontMetrics font = g.getFontMetrics();
	int px = (int)(w*scale/2-font.getStringBounds("8", g).getWidth()/2);
	int py = (int)(h*scale/2+(font.getAscent()-font.getDescent())/2);
	g.drawString("8",px,py);

    }

    public void paintComponent(Graphics g)
    {	super.paintComponent(g);
	Graphics2D g2 = (Graphics2D)g;
	g2.fillRect(0, 0, w*scale-1, h*scale-1);
	g2.scale(5, 5);
	g2.drawImage(bimg, 0, 0, this);
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jul 18 2011
Added on Jun 18 2011
10 comments
2,804 views