繁体   English   中英

不需要的透明JFrame背景

[英]unwanted transparent JFrame background

public void paint(Graphics g){
    g.setColor(Color.red);
    g.drawString("hello",50,50);
}

框架的背景看起来很奇怪而且透明。 仅当我绘制字符串时才会出现此问题,但是当我绘制矩形或任何其他形状时,框架看起来不错。

这是代码:

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);
    }
}

结果是:

在此处输入图片说明

感谢您的帮助 。 我找到了答案。 发生问题是因为我没有在paint方法中将对象(g)传递给构造函数

这是整个代码:

导入java.awt.Color;

导入java.awt.FlowLayout;

导入java.awt.Graphics;

导入javax.swing.JFrame;

B类扩展了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 static void main(String[] args) {

    B obj = new B();

}

}

无论如何,谢谢您的帮助。

奇怪,在我这里一切都很好。 尝试在构造函数中使用:

super("programme");

而是setTitle("programme"); 如果不起作用,请添加

setBackground(Color.lightGray);

在构造函数中。

无论如何,当您要绘制String时,应该使用JLabel类。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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