将函数传递给类

时间:2015-02-19 03:43:37

标签: java function

我有一个使用swing实现的java表单,我希望在其中放置一些可以使用graphics2D包绘制的面板。

为此,我使用JPanel的扩展来实现面板:

public class GraphicsPanel  extends JPanel
{

    public void paintComponent(Graphics g)
    {
        Graphics2D g2d = (Graphics2D) g;
        super.paintComponent(g2d);

        // Need to specify a function from the calling class here
        MethodFromCallingClass();
    }
}

在调用类中我有

public GraphicsPanel Graphics1= new GraphicsPanel() ;

public void Graphics1_Paint()
{
   // Code to draw stuff on the Graphics1 panel
}

所以问题是如何将函数(Graphics1_Paint)从调用类传递给GraphicsPanel类?

我已经尝试过阅读有关接口和lambda的内容,但到目前为止它们毫无意义。

请有人赐教。

3 个答案:

答案 0 :(得分:1)

我认为最简单的方法是将调用类(或其他一些接口)传递给GraphicsPanel的构造函数

public class GraphicsPanel extends JPanel {
    private CallingClass cc;
    public GraphicsPanel(CallingClass cc) {
        this.cc = cc;
    }
    public void paintComponent(Graphics g) {
        Graphics2D g2d = (Graphics2D) g;
        super.paintComponent(g2d);    
        cc.MethodFromCallingClass(); // <-- invoke a call-back.
    }
}

答案 1 :(得分:0)

因此,您可能希望定义在自定义JPanel类之外绘制的内容,您可以随时将所需内容传递给JPanel实例。这是可能的。

首先,定义一个包含一个使用Graphics2D实例绘制的方法的接口:

public interface DrawGraphics()
{
    public void draw(Graphics2D g);
}

接下来,您希望将GraphicsPanel扩展一下,以便能够更改DrawGraphics的基础实例。

所以你的构造函数现在应该是:

public GraphicsPanel(DrawGraphics graphicsToDraw) { ...

您还应该为DrawGraphics存储一个set方法,以便随时更改:

public void setDrawGraphics(DrawGraphics newDrawGraphics) { ...

请确保在此处的某处添加一些同步,或在EDT上创建所有DrawGraphics,因为paintComponents方法将在EDT上执行。

接下来,paintComponents方法可以简单地绘制图形:

public void paintComponent(Graphics g)   
{
    Graphics2D g2d = (Graphics2D) g;
    super.paintComponent(g2d);

    // Need to specify a function from the calling class here
    graphicsToDraw(g2d);
}

当您需要更改DrawGraphics

// Calling from the EDT
myGraphicsPanel.setDrawGraphics(g -> g.drawString("Hello World!", 50, 50);

答案 2 :(得分:0)

我似乎已经解决了这个问题,但我想对可用性和良好做法发表评论

 public class CallingClass
  {
   public JPanel Graphics1 ;

   public CallingClass()
    {

       Graphics1 = new Graphics1_Paint();
    }

  public class Graphics1_Paint extends JPanel
   {
    public Graphics2D g2d;

    public void paintComponent (Graphics g)
    {
        g2d = (Graphics2D) g;
        super.paintComponent(g2d);
        g2d.drawString("From Calling Class",10,10);
    }

  }

public static void main(String[] args){
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new CallingClass();}
    });
}

public class CallingClass { public JPanel Graphics1 ; public CallingClass() { Graphics1 = new Graphics1_Paint(); } public class Graphics1_Paint extends JPanel { public Graphics2D g2d; public void paintComponent (Graphics g) { g2d = (Graphics2D) g; super.paintComponent(g2d); g2d.drawString("From Calling Class",10,10); } } public static void main(String[] args){ SwingUtilities.invokeLater(new Runnable() { public void run() { new CallingClass();} }); }

似乎我毕竟不需要我的GraphicsPanel课程。