Search...
FAQs
Subscribe
Pie
FAQs
Recent topics
Flagged topics
Hot topics
Best topics
Search...
Search within Swing / AWT / SWT
Search Coderanch
Advance search
Google search
Register / Login
Post Reply
Bookmark Topic
Watch Topic
New Topic
programming forums
Java
Mobile
Certification
Databases
Caching
Books
Engineering
Micro Controllers
OS
Languages
Paradigms
IDEs
Build Tools
Frameworks
Application Servers
Open Source
This Site
Careers
Other
Pie Elite
all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Campbell Ritchie
Jeanne Boyarsky
Ron McLeod
Paul Clapham
Liutauras Vilda
Sheriffs:
paul wheaton
Rob Spoor
Devaka Cooray
Saloon Keepers:
Stephan van Hulst
Tim Holloway
Carey Brown
Frits Walraven
Tim Moores
Bartenders:
Mikalai Zaikin
Forum:
Swing / AWT / SWT
Text surrounded by a rectangle
Ryan Filz
Greenhorn
Posts: 3
posted 18 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
I am trying to use
Java
's Graphics.drawText and drawRectangle methods to draw a piece of text inside a rectangle. I was wondering if there was an easy way to do this with a surround method or something similar.
Craig Wood
Ranch Hand
Posts: 1535
posted 18 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
import java.awt.*; import java.awt.font.*; import javax.swing.*; public class InnerText extends JPanel { protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); int w = getWidth(); int h = getHeight(); int x = w/3; int y = h/4; int rectW = w*3/8; int rectH = h/4; g.setColor(Color.red); g.drawRect(x, y, rectW, rectH); Font font = g2.getFont().deriveFont(16f); g2.setFont(font); String text = "hello world"; FontRenderContext frc = g2.getFontRenderContext(); int textWidth = (int)font.getStringBounds(text, frc).getWidth(); LineMetrics lm = font.getLineMetrics(text, frc); int textHeight = (int)(lm.getAscent() + lm.getDescent()); int sx = x + (rectW - textWidth)/2; int sy = (int)(y + (rectH + textHeight)/2 - lm.getDescent()); g.setColor(Color.blue); g.drawString(text, sx, sy); } public static void main(String[] args) { JFrame f = new JFrame(); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.getContentPane().add(new InnerText()); f.setSize(400,400); f.setLocation(200,200); f.setVisible(true); } }
Ryan Filz
Greenhorn
Posts: 3
posted 18 years ago
Number of slices to send:
Optional 'thank-you' note:
Send
Thank you for your quick reply, your code helped out a lot!!
Consider Paul's
rocket mass heater
.
reply
reply
Bookmark Topic
Watch Topic
New Topic
Boost this thread!
Similar Threads
Center text on an image
Clip text in Rectangle
Swing related
Part II deployment diagram notation
transparent fillRect possible?
More...