2012-12-03 54 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();  
    } 
} 
相關問題