我试图将代码形式一个按钮放入一个类中,但在测试过程中我注意到我的表单上的面板没有更新。将面板直接设置为按钮时,它可以正常工作(参见buttons2的代码)。
button1代码......
private void button1_Click(object sender, EventArgs e)
{
SpecialPanelBuilder spb = new SpecialPanelBuilder();
panel1 = spb.PopulatedPanel();
}
特别小组班......
public class SpecialPanelBuilder
{
public Panel PopulatedPanel()
{
Panel p = new Panel();
Graphics g;
int size = 30;
int TextLeft = size;
//int LeftStartBox =
g = p.CreateGraphics();
g.FillRectangle(Brushes.Red, 10, 10, size, size);
g.DrawRectangle(new Pen(Color.Black), 10, 10, size, size);
g.DrawString(("test"), new Font("Arial", size /2, FontStyle.Bold),
Brushes.Black,
(size + TextLeft),
(size) - (-2));
g.FillRectangle(Brushes.Orange, 300, 10, size, size);
g.DrawRectangle(new Pen(Color.Black), 300, 10, size, size);
g.DrawString(("test"), new Font("Arial", size / 2, FontStyle.Bold),
Brushes.Black,
(size + TextLeft + 300),
(size) - (-2));
g.FillRectangle(Brushes.Green, 600, 10, size, size);
g.DrawRectangle(new Pen(Color.Black), 600, 10, size, size);
g.DrawString(("test"), new Font("Arial", size/2, FontStyle.Bold),
Brushes.Black,
(size + TextLeft + 600),
(size) - (-2));
return p;
}
按钮2代码,其中包含来自该类的所有代码...
private void button2_Click(object sender, EventArgs e)
{
int size = 30;
int TextLeft = size;
//int LeftStartBox =
Graphics g;
g = panel1.CreateGraphics();
g.FillRectangle(Brushes.Red, 10, 10, size, size);
g.DrawRectangle(new Pen(Color.Black), 10, 10, size, size);
g.DrawString(("Below Threshold"), new Font("Arial", size / 2, FontStyle.Bold),
Brushes.Black,
(size + TextLeft),
(size) - (-2));
g.FillRectangle(Brushes.Orange, 300, 10, size, size);
g.DrawRectangle(new Pen(Color.Black), 300, 10, size, size);
g.DrawString(("Less than 20% above threshold"), new Font("Arial", size / 2, FontStyle.Bold),
Brushes.Black,
(size + TextLeft + 300),
(size) - (-2));
g.FillRectangle(Brushes.Green, 600, 10, size, size);
g.DrawRectangle(new Pen(Color.Black), 600, 10, size, size);
g.DrawString(("On Order"), new Font("Arial", size / 2, FontStyle.Bold),
Brushes.Black,
(size + TextLeft + 600),
(size) - (-2));
}
答案 0 :(得分:1)
好吧,我不确定是对的但是在按钮2中你的图形对象g是用panel1.CreateGraphics()设置的,而button1.Code则不是这样。所以你实际上正在使用内部面板变量的图形对象。