繁体   English   中英

为什么 draw() 方法中的 repaint() 不起作用(不调用paint())?

[英]Why doesn't repaint() in the draw() method work (doesn't call paint())?

我正在创建一个类,它直接在屏幕上绘制黑色矩形。 我该如何修复它以使其正常工作?

public class BlackRectangle {
    public Rectangle rectangle = new Rectangle(0, 0, 0, 0);

    public BlackRectangle() {
        w.setAlwaysOnTop(true);
        w.setBounds(w.getGraphicsConfiguration().getBounds());
        w.setBackground(new Color(0, true));
        w.setVisible(true);
    }

    public void draw(int x, int y, int width, int height) {
        rectangle.setBounds(x, y, width, height);
        w.validate();
        w.repaint();

    }

    Window w = new Window(null) {
        @Override
        public void paint(Graphics g) {

            g.setColor(Color.BLACK);
            ((Graphics2D) g).fill(rectangle);
             g.dispose();
        }

        @Override
        public void update(Graphics g) {
            paint(g);
        }

    };

    public void clear() {
        rectangle.setBounds(0, 0, 0, 0);
    }

    public static void main(String[] args) {
        BlackRectangle rect = new BlackRectangle();
        rect.draw(10, 70, 60, 50);

    }

}

Slowpoke 答案.. 它在将 Window 更改为透明 JFrame 并绘制 Rectangle 以添加具有黑色背景的 Jpanel 后工作,如下所示:

public class BlackRectangle extends JPanel {


public BlackRectangle() {
    new JPanel();
    setBackground(Color.BLACK);
    setVisible(true);
}

public void setNew(int x, int y, int width, int height) {
    setBounds(x, y, width, height);
}


public void clearPanel() {
    setBounds(0, 0, 0, 0);
}

}


   public class FrameTransparent extends JFrame{

public FrameTransparent() {
    new JFrame();
    setAlwaysOnTop(true);
    setUndecorated(true);
    setBackground(new Color(0, 0, 0, 0));
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(null);
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    setSize(screenSize);
    setLocationRelativeTo(null);
    setVisible(true);
  }
}


public class Main {

public static void main (String [] args){
    new Main();
}
public Main(){
    BlackRectangle blackRectangle = new BlackRectangle();
    FrameTransparent frameTransparent = new FrameTransparent();
    frameTransparent.add(blackRectangle);
    blackRectangle.setNew(10, 70, 200, 200);
    frameTransparent.revalidate();
    frameTransparent.repaint();
   }

 }

暂无
暂无

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

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