2012-12-03 35 views
0

这里是一流的如何使用一个类的方法在另一类

 // extending class from JPanel 
    public class MyPanel extends JPanel { 
// variables used to draw oval at different locations 
    int mX = 200; 
    int mY = 0; 

// overriding paintComponent method 
    public void paintComponent(Graphics g) { 
// erasing behaviour – this will clear all the 
// previous painting 
     super.paintComponent(g); 
// Down casting Graphics object to Graphics2D 
     Graphics2D g2 = (Graphics2D) g; 
// changing the color to blue 
     g2.setColor(Color.blue); 

// drawing filled oval with blue color 
// using instance variables 
     g2.fillOval(mX, mY, 40, 40); 

现在我想使用的方法g2.setColot(Colot.blue)在下列其中问号的。

// event handler method 

public void actionPerformed(ActionEvent ae) { 

// if ball reached to maximum width of frame minus 40 since diameter of ball is 40 then change the X-direction of ball 

    if (f.getWidth() - 40 == p.mX) { 
     x = -5; 
????? set the color as red ???????? 

    } 

回答

0

如果我明白你需要的是使Graphics2D g2成为一个类属性。这样,在你的类的所有方法可以访问“全局”变量:

public class MyPanel extends JPanel { 
    Graphics2D g2; 

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

    public void actionPerformed(ActionEvent ae) { 
     g2.setColor(...); 
    } 
} 
1

一个Color成员添加到您的类。当您想要更改颜色时,请更改成员的值并致电repaint()

public class MyPanel extends JPanel { 
     int mX = 200; 
     int mY = 0; 
     Color myColor = Color.blue; //Default color is blue, 
            //but make it whatever you want 

    public void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     Graphics2D g2 = (Graphics2D) g; 
     g2.setColor(myColor); 

     g2.fillOval(mX, mY, 40, 40); 
    } 


public void actionPerformed(ActionEvent ae) { 

    if (f.getWidth() - 40 == p.mX) { 
     x = -5; 
     myColor = Color.red; 
     repaint();  
    } 
} 
相关问题