【问题标题】:Errors With Jpanel And GraphicsJpanel 和图形的错误
【发布时间】:2013-05-28 15:03:54
【问题描述】:

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

        }
    });
}


}

【问题讨论】:

  • Paint 应该在 createandshow 里面,还有什么错误?
  • 这是错误:线程“AWT-EventQueue-0”中的异常java.lang.Error:未解决的编译问题:main 类型中的方法paint(Graphics) 不适用于参数( )

标签: java swing graphics jpanel paint


【解决方案1】:

在 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());

【讨论】:

  • 我该怎么做?我应该扩展 Jcomponent 吗?
  • 那么我是否应该将它作为一个单独的课程与我已有的课程分开?
  • 这里的“g”有错误 javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); super.paintComponent(g);跨度>
  • 不要直接拨打paintComponent。请致电repaint。事实上,当应用程序第一次可见时,甚至不需要调用repaint
  • 但如果我不叫它什么都不会发生
猜你喜欢
  • 2011-10-17
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 2019-07-19
  • 2014-11-02
  • 2011-12-11
相关资源
最近更新 更多