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

    }
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 に答える