简体   繁体   中英

unwanted transparent JFrame background

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:

在此处输入图片说明

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM