[英]Java GUI Creating Components
我希望用正確的術語說GUI中的組件就像JButton,JPanel,JTextField之類的好東西。
我想創建一個接受整數的文本字段。 然后可以按下提交按鈕,並根據輸入的整數在彈出窗口中創建這么多的文本字段。
我不知道,有人可以引導我朝正確的方向發展嗎?
我遇到的麻煩是我不知道如何創建for循環來創建GUI組件。 我的意思是,如果我有一個for循環並執行以下操作:
print("JTextField num1 = new JTextField()");
然后在for循環中,當我需要很多時,它只會創建1個文本字段。 我一般如何創建JTextFields的變量?
謝謝你的幫助...
使用適當的LayoutManager(例如GridLayout)來創建和添加文本字段。
for (i = 0; i < numberOfTextFields; i++) {
JTextField textField = new JTextField();
container.add(textField);
/* also store textField somewhere else. */
}
嘗試這樣的事情:
List<JTextField> nums = new ArrayList<JTextField>();
JTextField tempField;
for (int i = 0; i < 10; i++) {
tempField = new JTextField();
jPanel1.add(tempField); // Assuming all JTextFields are on a JPanel
nums.add(tempField);
}
不要忘記為容器設置適當的布局管理器。 (在這種情況下為jPanel1)
我將創建一個列表來存儲文本字段,然后可以通過索引將它們取回。 然后,您可以根據需要擁有任意多個字段。
List fields = new ArrayList();
// Create as many elements as you need
for (int i = 0; i < numberOfElements; i++){
JTextField field = new JTextField();
// Add the fields to some panel so they are shown in the screen.
// I assume that the component is called parent panel
parentPanel.add(field);
// Store the component in the list so you can retrieve it later
fields.add(field);
}
// ...
// When you want to retrieve a particular one:
JTextField field = (JTextField)fields.get( indexToRetrieve );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.