Name convention on Java Swing components(prefix)

后端 未结 4 1108
忘掉有多难
忘掉有多难 2021-02-06 00:46

An question that was brought to my mind when programming with Swing in Java was, is it a recommendation or an \"official\"/most used naming convention(prefix) on Swing component

4条回答
  •  温柔的废话
    2021-02-06 00:55

    People will tell you that using prefixes is bad, because that is Hungarian notation and nowadays, Hungarian notation is considered a big no-no in programming. Personally, as somebody who has done a certain amount of GUI work, I can tell you that, whereas Hungarian notation should definitely be avoided in non-GUI programming, when doing GUIs it's a very good practice.

    Consider, for example, a simple form with a textbox which is to be used to enter the user's name. In front of this textbox should be a label prompting the user to enter his name in the textbox. Now, how are you going to name the textbox? 'Name'? What about the label? A good practice should be prefixing the textbox with txt, and label with label, which is what Hungarian notation is all about. Thus, the textbox is now named 'txtName' and the corresponding label is named 'lblName'. This gives you the additional benefit of easily accessing your textboxes, combo boxes and other widgets when in your IDE's editor. For example, typing 'txt' and pressing CTRL+Space in Eclipse opens up a context menu listing all of your textboxes, if you follow this notation.

    Now, to answer your question. The usual way to define what three letters you should use for a prefix is to remove all the vowels from the widget's name and also all repeating consonants. If there are more then three consonants left, they should be ignored. Therefore, a textbox (or TextField, or whatever this widget is called in your preferred widget toolkit) becomes 'txt', a label 'lbl', a combo box 'cmb', a table 'tbl' and so on.

提交回复
热议问题