0

I have a problem which I for the life of me I cannot figure out. I ask for user input and then it makes a JFrame and shows the word. I want to display the word at (0,0) but this appears to be out of the field, and writing up in the top where the Title is. Here is my code:

import java.util.Scanner;
import javax.swing.*;

public MainWindow(String input){
    JFrame frame = new JFrame();
    frame.setSize(320, 240);
    frame.setTitle("Draw String Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    Text text = new Text(input);
    frame.add(text);
    frame.setVisible(true); 
}

Scanner sc = new Scanner(System.in);
    System.out.print("Enter a string: ");
    String input = sc.nextLine();

    new MainWindow(input);
}
}

Then in my Text class:

import java.awt.*;
import javax.swing.JComponent;

public class Text extends JComponent {
String text;

public Text(String txt){
    this.text = txt;
}

public void paintComponent(Graphics g){
    Graphics2D g2d = (Graphics2D) g;
    g2d.drawString(this.text, 0, 5);
}
}

So, if you run this you will see the bottom half of, for instance, hello.

if I set

this.text, 10, 10

then you can see the whole word.

Is there a way, to make (0,0) start at the top left most corner and have the text be completely inside the actual draw area?

Abraxas
  • 11
  • 4

2 Answers2

2

You can translate() the origin of the graphics context so that it appears at the coordinates you specify. Subsequent calls to drawString(…, 0, 0) will render text with the baseline at those coordinates. Use FontMetrics to determine what coordinates to use. Examples shown here and here pass the coordinates to drawString(), but you can pass them to translate() instead. Be sure to restore the origin when you're done.

FontMetrics fm = g2d.getFontMetrics();
g2d.translate(0, fm.getAscent());
g2d.drawString(this.text, 0, 0);
g2d.translate(0, 0);
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
1

Use a Flow Layout or a Grid Layout to your JFrame and add a JLabel to set the text.

JFrame frame = new JFrame();
frame.setLayout(new FlowLayout());

JLabel label = new JLabel();
label.setText("Text");
frame.add(label);
frame.setVisible(true);