Java AWT drawString() does not display on window
awt, java
Solution
The problem you're having is the fact that you are painting directly on top of the frame. The frame also includes the frame border, so position 0, 0 (or in your case 10, 10) is actually hidden UNDER the frame border.
You can see more about that here.
Instead, you should draw onto a `Canvas` and add that to the frame
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public class BadFrame {
public static void main(String[] args) {
new BadFrame();
}
public BadFrame() {
Application app = new Application();
app.setSize(new Dimension(640, 480));
app.setTitle("This is a test");
app.setLayout(new BorderLayout());
app.add(new MyCanvas());
app.setVisible(true);
}
class MyWindowAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
public class MyCanvas extends Component {
@Override
public void paint(Graphics g) {
super.paint(g);
System.out.println("Hey hey !");
g.drawString("Test", 10, 10);
}
}
class Application extends Frame {
public Application() {
addWindowListener(new MyWindowAdapter());
}
}
}
The next question that comes to mind is, why AWT? The API has being moth balled in favor of Swing. If nothing else, it's automatically double buffered ;)
ps- You may also find 2D Graphics of some interest, especially the discussion on text
Problem
I am following the examples from `Java : The complete reference 8th edition (JDK 7)` on AWT and I cannot succeed to display a string on the window that appears. The size and title are set correctly and the window shows up. If I output a string on the console in the paint() method I see that it actually gets called a few times but the string does not appear on the window of my application. I can't see where I diverged from the example; I actually have a bit less code (they added a mouse listener and a key listener) :\ ``` import java.awt.Dimension; import java.awt.Frame; import java.awt.Graphics; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; public class Main { public static void main(String[] args) { Application app = new Application(); app.setSize(new Dimension(640, 480)); app.setTitle("This is a test"); app.setVisible(true); } } class MyWindowAdapter extends WindowAdapter { public void windowClosing(WindowEvent we) { System.exit(0); } } class Application extends Frame { public Application() { addWindowListener(new MyWindowAdapter()); } public void paint(Graphics g) { System.out.println("Hey hey !"); g.drawString("Test", 10, 10); } } ```