我正在使用NetBeans開發Java應用程序。我在JFrame
中有5 JTextFields
和2 JTextArea
。我想用循環立即清除它們。如何做呢?如何使用循環清除jframe的所有文本字段?
回答
遍歷所有的組分和所有JTextField
和JTextArea
對象的文本設置爲空字符串:
//Note: "this" should be the Container that directly contains your components
//(most likely a JPanel).
//This won't work if you call getComponents on the top-level frame.
for (Component C : this.getComponents())
{
if (C instanceof JTextField || C instanceof JTextArea){
((JTextComponent) C).setText(""); //abstract superclass
}
}
但textarea不清除。 –
對於模糊不清,我表示歉意。對getComponents()的調用應該在包含所有組件的JPanel上進行,而不是頂層Frame,它的add(Component)方法實際上將組件添加到嵌套在JRootPane中的JPanel(因此它的getComponents()方法將只返回JRootPane)。我已經測試過這個方法,它完美的工作。 – ApproachingDarknessFish
沒有明白。它不工作,只返回JRootPane。我在JFrame上試過這個...有什麼建議嗎? Component [] components = jframe.getRootPane()。getComponents(); –
適當的代碼應該是這樣一個
Component[] components = jframe.getContentPane().getComponents();
for (Component component : components) {
if (component instanceof JTextField || component instanceof JTextArea) {
JTextComponent specificObject = (JTextComponent) component;
specificObject.setText("");
}
}
- 1. 使用for循環清除所有文本字段?
- 2. 如何在java中使用for循環清除文本字段
- 3. 如何使用foreach循環清除所有文本框?
- 4. __doPostBack清除所有文本字段
- 5. 清除所有JFrame選擇
- 6. 使用javascript清除所有HTML字段
- 7. 如何使禁用文本字段上的文本清除
- 8. 清除所有字段
- 9. 循環功能清除字段
- 10. 如何清除文本字段?
- 11. 如何清除文本字段
- 12. 如何使用AS3清除焦點上的文本字段?
- 13. 清除html文本字段
- 14. 如何在foreach循環中清除列表的字段?
- 15. 清除EditText字段中的所有文本按鈕
- 16. 如何刪除使用for循環的所有檢查文件?
- 17. UI自動清除帶有「清除按鈕」的文本字段
- 18. 如何使用jQuery清除DIV中的所有文本框?
- 19. 如何清除for循環中的所有jTextField?
- 20. 如何使用循環獲取文本字段中的值?
- 21. 如何使用Netbeans在JFrame中顯示文本?如何清除JFrame中的文本?
- 22. 如何使用JavaScript條件清除文本字段?
- 23. 如何使用UIAutomation清除文本字段
- 24. 如何使用代理功能清除文本字段
- 25. 如何使用webdriver爲safaridriver清除文本框字段?
- 26. Onload清除所有文本字段jquery js
- 27. 如何使用swift 3中的按鈕清除文本字段中的文本?
- 28. 如何從文本區域清除所有以前的文本?
- 29. 如何確保repaint()清除Jframe的所有內容?
- 30. 如何清除背部片段中的文本字段?
使用'.getContentPane( ).getComponents()'在JFrame上獲取它的子級數組。迭代該數組,併爲每個項檢查'instanceOf TextComponent'如果是這樣,調用'setText(null)' –