简体   繁体   中英

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

I'm creating a class, which draws black rectangles over the screen directly. How can I fix it to make it work?

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 answer.. it worked after changing Window to transparent JFrame and drawing Rectangle to adding Jpanel with black background like this:

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

 }

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