2008/02/19(Tue) 08:26:47 編集(投稿者)
すみません、解決済みにチェックしてしまいましたが、もう一つ質問させていただきたいです。
先日回答していただいたコードより少し改良しようと思い、
「ボタンを押すと、panel1の中に入っているpanel2上に折れ線が描画される」
というものにしようとしました。
その際、DrawingMODというクラスを作り、そこにデリゲートを作成しました。
そして、Formのコード上にある、ボタンをクリックするイベントに、折れ線を描くというイベントとイベントハンドラの関連付けを行いました。
しかし、問題画発生しました。Form1のコードの最初に定義している、
//描画に使用する3点の座標 (データベースからクエリされたものと仮定)
private float xOne = 50.01f;
private float yOne = 100.01f;
private float xTwo = 100.01f;
private float yTwo = 100.01f;
private float xThree = 120.01f;
private float yThree = 120.01f;
が「変数が定義されているが一度も使われていない」というふうにWarningで出てしまいます。
英語のメッセージなのですが、
「Warning 1 The private field 'test_panel.Form1.xOne' is assigned but its value is never used」
となってしまいます。以下にDrawingMODクラスのコードとForm1のコードをお知らせします。
私としては、PaintEventArgsのeの取り扱い方に問題があるのではないかと思うのですが、よくわかっていません。
試しにコードを走らせると、panel2上に3本描かれるべき折れ線のうち、最初のもののみが描かれました。
また、再描画されなくなってしまいました。
どこに問題があるのか、ご指摘いただけないでしょうか。よろしくお願いします。
【DrawingMODクラスのコード】
public delegate void DrawOnPanel(object sender, PaintEventArgs e);//デリゲート
class DrawingMOD
{
public event DrawOnPanel DrawPanel; //イベントフィールド
private Control m_control;
//コンストラクタ
public DrawingMOD(Control c)
{
this.m_control = c;
}
//パネルに折れ線を描画するメソッド
public void DrawMovingObjects()
{
PaintEventArgs e = new PaintEventArgs(m_control.CreateGraphics(), m_control.ClientRectangle);
this.DrawPanel(this.m_control, e);
e.Graphics.Dispose();
}
}
【Form1のコード】
public partial class Form1 : Form
{
DrawingMOD myDraw; //Form1で共通に使用するオブジェクト変数の宣言
//描画に使用する3点の座標 (データベースからクエリされたものと仮定)
private float xOne = 50.01f;
private float yOne = 100.01f;
private float xTwo = 100.01f;
private float yTwo = 100.01f;
private float xThree = 120.01f;
private float yThree = 120.01f;
public Form1()
{
InitializeComponent();
this.myDraw = new DrawingMOD(this.panel2);
myDraw.DrawPanel += new DrawOnPanel(myDraw_DrawPanel);
}
private void button1_Click(object sender, EventArgs e)
{
this.myDraw.DrawMovingObjects();
}
//myDraw_DrawPanelイベントハンドラ
private void myDraw_DrawPanel(object sender, PaintEventArgs e)
{
//パネルのインスタンスを作成
Panel panel2 = sender as Panel;
this.panel2.AutoSize = true;
//set the background color
e.Graphics.Clear(Color.Black);
//Initialize the coordinates
float xOne = 50.01f;
float yOne = 100.01f;
float xTwo = 100.01f;
float yTwo = 100.01f;
float xThree = 120.01f;
float yThree = 120.01f;
//ペンの色を定義
int cRed = 200;
int cGreen = 100;
int cBlue = 100;
Pen pen = new Pen(Color.FromArgb(cRed, cGreen, cBlue), 4); //ペンを作成
//折れ線に使用する3点をPointF[]に格納する
PointF[] myPoints = new PointF[3];
myPoints[0] = new PointF(xOne, yOne);
myPoints[1] = new PointF(xTwo, yTwo);
myPoints[2] = new PointF(xThree, yThree);
for (int i = 0; i < 3; i++)
{
pen.EndCap = LineCap.ArrowAnchor; //折れ線を矢印にする
e.Graphics.DrawLines(pen, myPoints); //折れ線を描く
//change the location for another line
xOne += 200f;
yOne += 200f;
xTwo += 200f;
yTwo += 200f;
xThree += 200f;
yThree += 200f;
//change the color of lines
cRed += 20;
cGreen += 40;
cBlue += 20;
}
}
}