尝试使用paint(Graphics g)代码时出现错误。您能否帮助解决代码,以便有一个带有3d矩形的窗口。谢谢!

private static void paint(Graphics g){
    g.draw3DRect(10, 10, 50, 50, true);


然后朝向底部:

public static void main(String[] args) {
    //Schedule a job for the event-dispatching thread:
    //creating and showing this application's GUI.
    javax.swing.SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            createAndShowGUI();
            paint();

        }
    });
}


}

最佳答案

在Java中,覆盖时不能降低方法的可见性。同样,实例方法不能设为static。必须是

@Override
public void paint(Graphics g){
    super.paint(g);
    g.draw3DRect(10, 10, 50, 50, true);
}


在Swing中,请勿在顶级窗口(例如JFrame)中进行自定义绘制。
而是创建JComponent的子类并覆盖paintComponent并确保调用super.paintComponent(g)



class MyComponent extends JComponent {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.draw3DRect(10, 10, 50, 50, true);
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(400, 300);
    }
}


不要忘记将新组件的实例添加到JFrame

frame.add(new MyComponent());

07-28 02:20
查看更多