0

想象一下,您有按钮,每次单击一个按钮时,它都会将文本写入文本框。

IE:

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button41.Click
        textbox.Text &= "1"
    End Sub

假设您有 10 个这些按钮作为数字(例如 0-9。)而不是一一处理这些按钮的单击事件(例如 buttonxclickevent 处理 textbox.text = x);是否有更优雅的方法来遍历这些按钮和事件?

4

3 回答 3

1

既然你已经展示了 VB.NET 代码,我会用 VB.NET 来回答。您可以为所有处理程序使用一个处理程序:

Public Class Form1

    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        For Each btn In Me.Controls.OfType(Of Button)()
            AddHandler btn.Click, AddressOf buttonClicked
        Next
    End Sub

    Private Sub buttonClicked(sender As Object, e As EventArgs)
        Dim btn As Button = DirectCast(sender, Button)
        TextBox1.Text &= "1"
    End Sub

End Class

Enumerable.OfType过滤器和强制转换,所以结果是IEnumerable(Of Button).

于 2012-10-04T14:45:34.273 回答
0

-让类实现ActionListener

-重写这样的actionPerformed() 方法来识别按钮并将消息相应地键入到JTextField.

JButton b1;
JButton b2;

public void actionPerformed(ActionEvent e) {
   if (e.getSource() == b1) {
      // Do something...
   }
   if (e.getSource() == b2) {
      // Do something else...
   }
}
于 2012-10-04T14:40:42.680 回答
0

可以通过这种方式完成:

Private Sub Button1_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) _
    Handles Button1.Click, Button2.Click, Button3.Click
        Dim b As Button = CType(sender, Button)
        Label1.Text = b.ID
End Sub
于 2012-10-04T14:47:11.410 回答