0

here is first class

     // 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);

now i want to use the method g2.setColot(Colot.blue) in the following where the question marks are.

// 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 ????????

    }
4

2 回答 2

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();    
    }
}
于 2012-12-03T20:38:04.600 回答
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(...);
    }
}
于 2012-12-03T20:34:18.577 回答