如何通过另一个类的图形对象调用函数? [英] How do I call a function with a graphics object from another class?

查看:49
本文介绍了如何通过另一个类的图形对象调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从 main()调用 paint(),但是我需要一个参数.我不知道要传递哪个参数,而且我似乎也无法当我在参数之外定义 g 时,请使用 Graphics 对象,因为无法对其进行初始化.

I want to call paint() from main() but I need a parameter.I don't know which parameter to pass and I can't seem to use the Graphics object when I define g outside the parameters since it can't be initialized.

我尝试在 main()中创建Graphics类的对象,然后将其作为参数传递,但是每当我尝试使用g时,它都会给我带来nullException

I tried creating an object of the Graphics class in main() and then passing it as a parameter but then whenever I try to use g it gies me a nullException

import java.util.*;
import java.awt.*;
import javax.swing.JFrame;
 class Boards extends Canvas
{
    JFrame frame;    
     void frame()
    {
        JFrame frame = new JFrame("SNAKES AND LADDERS");
        Canvas canvas= new Boards();
        canvas.setSize(1000,1000);
        frame.add(canvas);
        frame.pack();
        frame.setVisible(true); 
        frame.getGraphics();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
        Graphics g;

    }
    public void paint(Graphics g)
    {
      g.fillRect(0,0,100,1000);
    }
}

 class snakes_and_ladders
{
    Scanner s= new Scanner (System.in);
    Boards board= new Boards();
     void main()    
    {
        board.frame();
        board.paint();
    }
}

推荐答案

您将需要调用

You will need to call repaint. From the docs:

public void repaint(long tm,整数x诠释整数宽度整型高度)

将指定区域添加到脏区域列表(如果该组件是显示.该组件将在所有当前待处理事件已调度.

Adds the specified region to the dirty region list if the component is showing. The component will be repainted after all of the currently pending events have been dispatched.

编辑

间接参数化的示例:

protected String test = "foo";

public void myRepaint(long tm, int x, int y, int width, int height, test) {
    this.test = test;
    repaint(tm, x, y, width, height);
}

public void paint(Graphics g) {
    //do something with this.test
}

这篇关于如何通过另一个类的图形对象调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆