2016-09-18 22 views
0

Я новичок в C#, и я пытаюсь понять концепцию z-index. Пока у меня есть простая форма, созданная с использованием проекта ConsoleApplication в visual studio. Есть 3 cs-файла. Вот код:C# bringtofront() и senttoback() не работает

В Algorithm.cs (унаследованный от UI.cs):

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Drawing; 

public class Algorithm : UI 
{ 
private Timer refresh = new Timer(); 


//Ball settings 
private const int offset = 25; 
private const int rate = 200; 
private int ball_bounding_box_x_coord; 
private int ball_bounding_box_y_coord; 
private int x; 
private int y; 
private const int width = 50; 
private const int height = 50; 
Brush brush = new SolidBrush(Color.Blue); 

public bool isStartClicked = false; 



Button test = new Button(); 
public Algorithm() 
{ 
    test.Text = "test"; 
    test.Location = new Point(0, 800); 
    test.Size = new Size(100, 50); 
    test.TabIndex = 0; 

    bottom.Controls.Add(test); 
    test.BringToFront(); 

    ball_bounding_box_x_coord = middle.Size.Width/2 - width/2; 
    ball_bounding_box_y_coord = middle.Size.Height/2 - height/2; 

    middle.Paint += new PaintEventHandler(Draw); 
    start.Click += new EventHandler(Start); 

} 

private void Calculate() 
{ 
    Graphics g = middle.CreateGraphics(); 
    //g.FillEllipse(brush,)   
} 




private void Draw(object sender, PaintEventArgs e) 
{ 
    e.Graphics.FillEllipse(brush, ball_bounding_box_x_coord , ball_bounding_box_y_coord , width, height); 
} 


public void Start(object sender, EventArgs e) 
{ 
    MessageBox.Show("Button clicked"); 
} 

} 

В UI.cs:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Drawing; 

public class UI : Form 
{ 
//Window settings 
private const int WINDOW_WIDTH = 1600; 
private const int WINDOW_HEIGHT = 900; 
private Panel top = new Panel(); 
public Panel middle = new Panel(); 
public Panel bottom = new Panel(); 
private Label title = new Label(); 

//Text box for degree input 
private Label degree_input_label = new Label(); 
private TextBox degree_input = new TextBox(); 
public double input; 

//Label to display x and y coordinates of the ball 
public Label ball_x_coord = new Label(); 
public Label ball_y_coord = new Label(); 

//Buttons 
public Button start = new Button(); 
private Button quit = new Button(); 


public UI() 
{ 
    //total height of 3 areas != window_height???????????????? 
    //Setup window form 
    this.Width = WINDOW_WIDTH; 
    this.Height = WINDOW_HEIGHT; 
    this.Text = "Project 2"; 


    //Add a badass title 
    title.Text = "Designed by Me"; 
    title.AutoSize = true; 
    title.Location = new Point(600, 20); 
    title.Font = new Font(title.Font.Name, 24, FontStyle.Bold); 
    title.BackColor = Color.Red; 
    Controls.Add(title); 

    top.Location = new Point(0, 0); 
    top.Size = new Size(WINDOW_WIDTH, 80); 
    top.BackColor = Color.Red; 

    middle.Location = new Point(0, top.Location.Y + top.Size.Height); 
    middle.Size = new Size(WINDOW_WIDTH, 680); 
    middle.BackColor = Color.Cyan; 




    bottom.Location = new Point(0, top.Location.Y + top.Size.Height + middle.Size.Height); 
    bottom.Size = new Size(WINDOW_WIDTH, WINDOW_HEIGHT - top.Height - middle.Height); 
    bottom.BackColor = Color.Green; 

    degree_input_label.Text = "Enter a degree:"; 
    degree_input_label.Location = new Point(100, bottom.Location.Y + 20); 
    degree_input_label.AutoSize = true; 
    Controls.Add(degree_input_label); 

    degree_input.Size = new Size(50, 50); 
    degree_input.Location = new Point(200, bottom.Location.Y + 20); 
    degree_input.Leave += new EventHandler(TextChange); 
    degree_input.TabIndex = 2; 
    Controls.Add(degree_input); 

    ball_x_coord.Text = "Ball X Coord"; 
    ball_x_coord.Location = new Point(400, bottom.Location.Y + 20); 
    ball_x_coord.AutoSize = true; 
    Controls.Add(ball_x_coord); 

    ball_y_coord.Text = "Ball y coord"; 
    ball_y_coord.Location = new Point(500, bottom.Location.Y + 20); 
    ball_y_coord.AutoSize = true; 
    Controls.Add(ball_y_coord); 


    start.Text = "Start"; 
    start.Location = new Point(1100, bottom.Location.Y + 20); 
    start.Size = new Size(100, 50); 
    start.TabIndex = 1; 
    Controls.Add(start); 

    quit.Text = "Quit"; 
    quit.Location = new Point(1400, bottom.Location.Y + 20); 
    quit.Size = new Size(100, 50); 
    quit.Click += new EventHandler(Quit); 
    Controls.Add(quit); 


    //ADD BACKGROUND CONTROLS 
    Controls.Add(top); 
    Controls.Add(middle); 
    Controls.Add(bottom); 









}//end constructor 


private void TextChange(object sender, EventArgs e) 
{ 
    if(degree_input.TextLength <= 0) 
    { 
     degree_input.Text = "0"; 
     MessageBox.Show("Please enter a degree"); 
     degree_input.Focus(); 
    }else 
    { 
     input = double.Parse(degree_input.Text); 
     //MessageBox.Show(input.ToString()); 
    } 

} 







void Quit(object sender, EventArgs e) 
{ 
    Application.Exit(); 
} 



} 

В Main.cs:

class Program 
{ 
static void Main(string[] args) 
{ 
    Algorithm al = new Algorithm(); 
    UI a = new UI(); 

    //Application.Run(a); 
    Application.Run(al); 
} 
} 

Проблема, с которой я столкнулась, заключается в том, что кнопка проверки не видна. Если я сниму нижнюю панель и добавлю тестовую кнопку непосредственно в форму, она будет видна. Почему он не появляется на нижней панели, даже после того, как я использовал функцию showtofront()?

+0

Прочтите [ask] и предоставьте [mcve], который воспроизводит проблему. Для всех, кого мы знаем, переменные, которые вы показываете, создают панель 0x0 или она находится за пределами ее контейнера, то есть вне поля зрения. – CodeCaster

+0

Где кнопка тестирования? Я не вижу ни одного теста имени кнопки или комментариев, которые упоминаются в этой кнопке. – mok

+0

@mok: его кнопка «a», a.Text = «test». Извините за беспорядок, отредактируйте. – Fierid

ответ

0

Почему он не отображается на нижней панели, даже после того, как я использовал функцию bringtofront()?

Потому что вы поместили его вне визуальной границы панели:

test.Location = new Point(0, 800); 

Это устанавливает положение кнопки на горизонтальное смещение 0 и вертикальное смещение 800. Панель bottom имеет высоту всего 140 пикселей, поэтому 800 - колодец внизу нижней части видимой области.

Это не совсем понятно, что вы хотели сделать. Учитывая, что ширина окна 1600 пикселей и 800 составляет половину, может быть, вы просто транспонировали X и координаты Y и имел в виду вместо этого:

test.Location = new Point(800, 0); 

Это было бы поместить кнопку в середине панели, выравниваются по Вверх.

Кроме этого, я не могу себе представить, почему, если вы хотите, чтобы кнопка была видимой, вы бы скорректировали местоположение для нее, которое не находится в видимой области.

+0

Спасибо, что решили проблему. Это было так небрежно. – Fierid