Java: Why doesn't this JPanel paint properly?

十年热恋 提交于 2020-01-06 14:51:28

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/18039172/java-why-doesnt-this-jpanel-paint-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!