Reputation:
Ive got a problem with placing String text in my frame, using paintComponent method.
It Looks like that:
I dunno why it doesn't want to place String in proper place, given that I've even counted pixels.
import java.awt.EventQueue;
import javax.swing.JFrame;
public class FrameMain {
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
JFrame frame = new DrawFrame();
frame.setVisible(true);
}
});
}
public class DrawFrame extends JFrame {
public DrawFrame()
{
setTitle("Frame with a component containing String");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds (100, 100, 300, 300 );
DrawComponent draw = new DrawComponent();
add(draw);
}
public class DrawComponent extends JComponent {
public void paintComponent(Graphics g) {
g.drawString("First string in component located in frame", WIDTH, HEIGHT);
final int WIDTH = 175;
final int HEIGHT = 200;
}
Upvotes: 1
Views: 51
Reputation: 324128
g.drawString("First string in component located in frame", WIDTH, HEIGHT);
//final int WIDTH = 175;
//final int HEIGHT = 200;
Never define a variable after you use it. WIDTH and HEIGHT are variables from other Swing class that default to 0.
final int WIDTH = 175;
final int HEIGHT = 200;
g.drawString("First string in component located in frame", WIDTH, HEIGHT);
Edit:
I want the String to set position given the size of frame, not position of it.
Don't do custom painting. Use a JLabel.
JLabel label = new JLabel("centered");
label.setHorizontalAlignment( JLabel.CENTER );
frame.add(label);
Upvotes: 3
Reputation: 209012
The Problem is you have
final int WIDTH = 175;
final int HEIGHT = 200;
declared after drawString(..., WIDTH, HEIGHT)
What is happening is that JComponent
also has a contant HEIGHT
and WIDTH
, so the drawString
is using the WIDTH
and HEIGHT
of JComponet
and not the ones you declared.
If you want to use yours, then just place it before the drawString
final int WIDTH = 175;
final int HEIGHT = 200;
g.drawString("First string in component located in frame", WIDTH, HEIGHT);
UPDATE
To center the text, you need to use FontMetrics
. See here
public void paintComponent(Graphics g) {
super.paintComponent(g);
String message = "First string in component located in frame";
Font font = new Font("impact", Font.PLAIN, 14);
g.setFont(font);
FontMetrics fm = g.getFontMetrics(font);
int stringWidth = fm.stringWidth(message);
int height = fm.getAscent();
int x = getWidth()/2 - stringWidth/2;
int y = getHeight()/2 + height/2;
g.drawString(message, x, y);
}
Upvotes: 2