Reputation: 11
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("hello",50,50);
}
the background of the frame looks strange and transparent. This problem only happens when I draw a string, but when I draw a rectangle or any another shape, the frame looks good.
this is the code:
import javax.swing.*;
import java.awt.*;
public class B extends JFrame {
public B() {
this.setTitle("programme");
this.setSize(400, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setVisible(true);
}
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawString("hello", 50, 50);
}
}
this is the result:
Upvotes: 0
Views: 148
Reputation: 11
Thank you for helping . I have found the answer. The problem happened because I didn't pass the object (g) to the constructor in paint method
This is the whole code :
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Graphics;
import javax.swing.JFrame;
class B extends JFrame {
public B() {
this.setTitle("programme");
this.setSize(400,200);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLayout(new FlowLayout());
this.setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
// I have added the previous line and it solved the problem
g.setColor(Color.red);
g.drawString("hello", 50, 50);
}
}
public class main {
public static void main(String[] args) {
B obj = new B();
}
}
Anyway thank you for helping.
Upvotes: 1
Reputation: 692
strange, at my place everythings works fine. Try in constructor use:
super("programme");
instead setTitle("programme");
if doesn't work add
setBackground(Color.lightGray);
in constructor.
Anyway, when you want to paint String you should use JLabel
class.
Upvotes: 0