Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

swing - Java - Calling paint method from different class?

I have a class which extends JFrame and creates a window and it needs to call the paint() method which is in a different class. I understand that if they were in the same class, the setVisible(true) would call the paint method, but since they are in different classes, it does not. I have created objects of the Die class (the one painting), but I don't know how to use them to call the paint method.

This is the class which creates the window:

public class Game extends Frame 
{

    public void window()
    {   
        setTitle("Roll");   //  Title of the window
        setLocation(100, 100);          //  Location of the window
        setSize(900, 600);              //  Size of the window
        setBackground(Color.lightGray); //  Color of the window
        setVisible(true);               //  Make it appear and call paint

    }

And for the paint method in the other class called Die, I used:

public void paint(Graphics pane)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If I understand your question you could pass the Die instance into the Game constructor with something like

public class Game extends Frame {
  private Die die;
  public Game(Die die) {
    this.die = die;
  }
  public void window() {    
    setTitle("Roll");   //  Title of the window
    setLocation(100, 100);          //  Location of the window
    setSize(900, 600);              //  Size of the window
    setBackground(Color.lightGray); //  Color of the window
    setVisible(true);               //  Make it appear and call paint
    die.setVisible(true);           //  The same
  }
}

Then, wherever you call new Game() you add the Die instance argument. This is a fairly common way to implement a callback in Java (and other OOP languages).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...