1

当我尝试使用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();

        }
    });
}


}
4

1 回答 1

5

在 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());
于 2013-05-28T15:17:22.327 回答