Results 1 to 5 of 5
Thread: Center text in a JComponent?
- 04-17-2011, 08:09 PM #1
The easiest way is to add a JLabel to it that has its horizontalAlignment property set to SwingConstants.CENTER. If you give the JComponent a BorderLayout and add the JLabel to the BorderLayout.CENTER position then it will fill the component. Otherwise, you may need to muck with FontMetrics, something I've not yet done.
- 04-17-2011, 09:01 PM #3
The JComponent isn't going to hold any other components though. The JComponent is just a canvas for the program to draw on, that's why im using drawString() to put the message on the screen. I also don't like messing with layout's I never got the hang of 'em. So I will look into FontMetrics and see what I can find about that. Thanks.
EDIT: Found a way using FontMetrics. Here is an example for future reference:
fontName = the name of the font you want to use
g = the graphics object your drawing on
width = the width of the area you want the text centered in
height = the height of the area you want the text centered in
Font font = new Font(fontName,Font.PLAIN,16); FontMetrics fm = g.getFontMetrics(font); g.drawString("Hello",(width - fm.stringWidth("Hello")) / 2,(height - font.getSize()) / 2);
Last edited by Zman3359; 04-17-2011 at 09:29 PM.
- 04-17-2011, 10:15 PM #4Senior Member
- Join Date
- Jul 2009
I also don't like messing with layout's I never got the hang of 'em.
- Rep Power
I agree with Fubarable, a JLabel is the way to go.
- 04-17-2011, 10:44 PM #5
- By tashimoto in forum New To JavaReplies: 2Last Post: 10-01-2010, 07:18 PM
- By sameer22 in forum CLDC and MIDPReplies: 0Last Post: 09-28-2010, 09:52 AM
- By ronaldrandon in forum New To JavaReplies: 2Last Post: 08-08-2010, 08:07 PM
- By nicacutenica in forum New To JavaReplies: 5Last Post: 06-29-2010, 06:50 PM
- By Marcus in forum Java AppletsReplies: 4Last Post: 06-08-2007, 06:15 AM