Shapes not drawing in Java

痴心易碎 提交于 2019-12-11 12:19:01

问题


Can anyone help me out and tell me why the rectangle will not appear? The frame runs fine, but no shapes show up. I have tried doing this a couple of different ways, including with two separate classes, but all I get is an empty frame.

import java.awt.Color;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Surface extends JPanel 
{

    public void paintComponent(Graphics2D g)
    {
        super.paintComponent(g);
        g.setColor(Color.RED);
        g.drawRect(100, 100, 30, 40);
    }

    public static void main(String[] args) 
    {
        Surface s = new Surface();
        JFrame jf = new JFrame();
        jf.setTitle("Tutorial");
        jf.setSize(600, 400);
        jf.setVisible(true);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.add(s);
        s.repaint();
    }
}

回答1:


If you want to override a method, then annotate it correctly:

@Override
public void paintComponent(Graphics2D g)
{
    super.paintComponent(g);
    g.setColor(Color.RED);
    g.drawRect(100, 100, 30, 40);
}

then your IDE should tell you, that you're not overriding the paintComponent method correctly, because your parameter type Graphics2D is wrong.

This is the signature of the original/parent method in JComponent:

protected void paintComponent(Graphics g)

And as you can see, it uses Graphics instead of Graphics2D. You're currently overloading paintCompoent instead of overriding it. So change your parameter type to Graphics (and import java.awt.Graphics) and it will work:

@Override
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    g.setColor(Color.RED);
    g.drawRect(100, 100, 30, 40);
}

By the way, you're setting the visibility of your jf first and then add something to its contentpane. In some case this can cause trouble and the added components won't be visible until you repaint the frame (or you do something else, which cause the frame to repaint itself, like calling pack()). So it might be best to switch the order of these method calls in your main method:

Surface s = new Surface();
JFrame jf = new JFrame();
jf.setTitle("Tutorial");
jf.setSize(600, 400);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(s);
//s.repaint(); // not needed anymore, because "jf" will repaint everything during the 'setVisible' call
jf.setVisible(true); // should almost always be the last thing you do


来源:https://stackoverflow.com/questions/30424127/shapes-not-drawing-in-java

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