Java:为什么JPanel不能正确绘制? [英] Java: Why doesn't this JPanel paint properly?

查看:140
本文介绍了Java:为什么JPanel不能正确绘制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个2D数组。我希望每个像素在实际图像中总共由四个像素表示。我已经尝试了各种代码,但没有一个可以工作,我也不太了解它是如何工作的。



到目前为止,我有:

  panel = new JPanel(){
@Override
public void paint(Graphics g){
Rectangle rect = g.getClipBounds();
g.setColor(Color.white);
g.fillRect(rect.x,rect.y,rect.width,rect.height); (int j = 0; j (int i = 0; i g.setColor(Color.red);
g.fillRect(j * 4,i * 4,4,4);
}
}
super.paint(g);
}
};
panel.repaint();

我哪里错了?

解决方案

重写 paint()不是最糟糕的事情,我强烈推荐重写 paintComponent()。另外,您必须使用 Graphics 调用 super.paint() 之前 >对象,而不是之后。它只是把你所有的工作都废掉了。



另外,我不知道你是否做了这个或者没有,因为你没有在你的代码中使用它,但确保将面板添加到 JFrame 或任何正在使用的窗口类中,以便实际显示。我希望这有助于。


I have a 2D array. I want each pixel to be represented by a total of four in the actual image. I've tried various piece of code but none seem to work and I don't really understand how it works either.

So far I have:

panel = new JPanel() {
            @Override
            public void paint(Graphics g) {
                Rectangle rect = g.getClipBounds();
                g.setColor(Color.white);
                g.fillRect(rect.x, rect.y, rect.width, rect.height);
                for (int i = 0; i < m.width(); i++) {
                    for (int j=0; j < m.height(); j++) {
                        g.setColor(Color.red);
                        g.fillRect(j*4, i*4, 4, 4);
                    }
                }
                super.paint(g);
            }
        };
        panel.repaint();

Where am I going wrong? The area stays completely grey with no colour!

解决方案

While overriding paint() is not the worst thing to do, I highly recommend overriding paintComponent() instead. Also, you must call super.paint() prior to doing your drawing using the Graphics object, not afterwards. It just scraps all of your work that way.

Also, I don't know if you did this or not, since you don't have it in your code, but make sure to add the panel to the JFrame or whatever window class you are using so it will actually show up. I hope this helps.

这篇关于Java:为什么JPanel不能正确绘制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆