[英]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.