简体   繁体   English

如何在图像图标上绘制黑色矩形?

[英]how to draw a black rectangle over Image icon?

in my application I have a cross road picture in the background and I want to draw traffic lights on the top of it (black rectangle with 3 circles) The problem is, I cannot see the rectangle at all, as if it was under the image or something. 在我的应用程序中,我在背景中有一个交叉路图片,我想在其顶部绘制交通信号灯(带有3个圆圈的黑色矩形)问题是,我完全看不到矩形,就好像它在图像下方或者其他的东西。 And if I switch the order in which the items are painted, I get all black image. 而且,如果我切换项目的绘制顺序,则会得到全黑图像。

Do you have any idea how this can be solved?I am new to graphics and searched similar questions, but none helped me. 您不知道该如何解决吗?我是图形新手,也搜索过类似的问题,但没有一个帮助我。 Thank you. 谢谢。

public MainFrame() throws HeadlessException {
    super("semafor");        
    crossroad = new ImageIcon("cross.png");

    initFrame();
    initComponents();

    sem1 = new Semafor(true, 100, 100);
    add(sem1);

    repaint();
    setVisible(true);
}

//here I paint the image
@Override
public void paint(Graphics g) {
    super.paint(g);
    g.drawImage(crossroad.getImage(), 0, 45, this);

}

//and in class Semafor i paint the actual traffic lights

@Override
public void paint(Graphics g) {
    g.setColor(Color.black);
    g.fillRect(0, 0, getWidth(), getHeight());
    g.setColor(Color.darkGray);

    //and then the circles
}

The first thing I'm noticing is that you are calling <unknown>.getWidth() and <unknown>.getHeight() for the rectangle size. 我要注意的第一件事是您正在调用<unknown>.getWidth()<unknown>.getHeight()作为矩形大小。 If it's covering the entire image, this suggests that it is getting that width and height from the panel it is being drawn on. 如果它覆盖了整个图像,则表明它是从要绘制的面板上获得该宽度和高度的。

A simple stack trace, 一个简单的堆栈跟踪

(new Exception).printStackTrace();

or 要么

Thread.dumpStack();

will tell you as much. 会告诉你很多。 You could also query the width and height with a System.out call to verify that you're getting the values you're expecting, or, if this really gets out of control, learn to use JUnit and the assert statement. 您还可以使用System.out调用查询宽度和高度,以验证您是否正在获取期望的值,或者,如果这确实失去了控制,请学习使用JUnit和assert语句。 Honestly, though, it looks like you're just accidentally calling the wrong method. 坦白说,看起来您只是在偶然地调用了错误的方法。

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

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