我正在创建一个类,该类直接在屏幕上绘制黑色矩形。我该如何修复它才能使其正常工作?
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);
}
}
答案 0 :(得分:0)
慢速回答..它在将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();
}
}