用户界面开发(C# 与 Java)
09/04/2008
本文内容
更新:2007 年 11 月
可以在 C# 中使用 .NET Framework 的丰富 Windows 窗体组件进行客户端窗体应用程序编程。
Java
大部分 Java 应用程序使用 Abstract Windowing ToolKit (AWT) 或 Swing(包括 AWT 事件模型)来进行窗体编程,而 Swing 使用 AWT 的基础结构。AWT 提供所有基本的 GUI 功能和类。
Java 示例
框架是带有标题和边框的窗口,通常用于添加组件。
JFrame aframe = new JFrame();
Component 类是具有图形表示形式的对象,它经常会被扩展;使用继承的方法也经常重写这些方法,如演示代码中的 Shape 组件的 paint 方法。
import java.awt.*;
import javax.swing.*;
class aShape extends JComponent {
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D)g;
// Draw the shape.
}
public static void main(String[] args) {
JFrame aframe = new JFrame();
frame.getContentPane().add(new aShape ());
int frameWidth = 300;
int frameHeight = 300;
frame.setSize(frameWidth, frameHeight);
frame.setVisible(true);
}
}
可以注册侦听器来侦听组件的操作事件,从而处理事件。例如,按下并释放某个按钮时,AWT 通过调用此按钮上的 processEvent 将一个 ActionEvent 实例发送到该按钮。此按钮的 processEvent 方法接收此按钮的所有事件,它通过调用自身的 processActionEvent 方法来继续传递操作事件。后一个方法将继续传递操作事件,将它传递给那些已注册为侦听此按钮生成的操作事件的操作侦听器。
C#
在 C# 中,.NET Framework 的 System.Windows.Forms 命名空间和类为 Windows 窗体开发提供一套全面的组件。例如,下面的代码使用 Label、Button 和 MenuStrip。
C# 示例
直接从 Form 类派生,如下所示:
public partial class Form1 : System.Windows.Forms.Form
添加您的组件:
this.button1 = new System.Windows.Forms.Button();
this.Controls.Add(this.button1);
下面的代码演示如何将标签、按钮和菜单添加到窗体。
namespace WindowsFormApp
{
public partial class Form1 : System.Windows.Forms.Form
{
private System.ComponentModel.Container components = null;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.MenuStrip menu1;
public Form1()
{
InitializeComponent();
}
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.label1 = new System.Windows.Forms.Label();
this.Controls.Add(this.label1);
this.button1 = new System.Windows.Forms.Button();
this.Controls.Add(this.button1);
this.menu1 = new System.Windows.Forms.MenuStrip();
this.Controls.Add(this.menu1);
}
static void Main()
{
System.Windows.Forms.Application.Run(new Form1());
}
}
}
与 Java 类似,在 C# 中可以注册侦听器来侦听组件的事件。例如,按下并释放按钮时,运行时会将一个 Click 事件传递给所有已注册为侦听该按钮的 Click 事件的侦听器。
private void button1_Click(object sender, System.EventArgs e)
{
}
例如,可以使用下面的代码来注册 button1_Click,以处理 Button 的实例(称为 button1)的 Click 事件。
// this code can go in InitializeComponent()
button1.Click += button1_Click;
请参见
概念
其他资源