java c# windows_用户界面开发(C# 与 Java)

本文探讨了C#和Java在Windows用户界面开发中的应用,介绍了C#中.NET Framework的Windows窗体组件以及Java的AWT和Swing。通过示例展示了在Java中创建JFrame和自定义组件以及在C#中使用Label、Button和MenuStrip组件的基本步骤。同时,文章提到了在两种语言中注册事件侦听器以响应用户操作的方法。
摘要由CSDN通过智能技术生成

用户界面开发(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;

请参见

概念

其他资源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值