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?