1. 功能
作為swing的組件,JList與JTextArea是不可以單獨實現滾動功能的,需要與JScrollPane結合才可以。
本代碼中:
JList實現從其它數據源獲取數據,然后依次對這些數據進行處理,處理過程中,在JList中選擇當前處理的記錄,依次向下移動。
JTextArea顯示處理結果,因為有很多數據,內容滿了的時候,需要滾動顯示,就是一直顯示最新的數據。
2. 實現代碼
注意:下面的代碼片段必須插入類的各相關段中,不是完整代碼。
// 代碼片段一,定義變量 private JList<String> jListAuthor; private JScrollPane jScrollPaneAuthor; private JScrollPane jScrollPaneInfo; private JTextArea jTextAreaInfo; // ......
// 代碼片段二,生成對象並加入到界面中 { { jListAuthor = new JList<String>(); } jScrollPaneAuthor = new JScrollPane(); // For ensureIndexIsVisible method to work, the JList must be within a JViewport. jScrollPaneAuthor.getViewport().setView(jListAuthor); getContentPane().add(jScrollPaneAuthor); jScrollPaneAuthor.setBounds(5, 5, 150, 403); jScrollPaneAuthor.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); } { { jTextAreaInfo = new JTextArea(); jTextAreaInfo.setText(""); jTextAreaInfo.setLineWrap(true); // 設置自動換行 // 設置斷行不斷字 // If set to true the lines will be wrapped at word boundaries (whitespace) if they are too long to fit within the allocated width. // If set to false, the lines will be wrapped at character boundaries. By default this property is false. jTextAreaInfo.setWrapStyleWord(true); } jScrollPaneInfo = new JScrollPane(jTextAreaInfo); getContentPane().add(jScrollPaneInfo); jScrollPaneInfo.setBounds(347, 0, 290, 403); } // ......
// 代碼片段三,獲取數據並填充左邊的JList TreeSet<String> ts = myService.getAuthors(); @SuppressWarnings({ "rawtypes", "unchecked" })
ListModel<String> jListModelAuthor = new DefaultComboBoxModel( ts.toArray()); jListAuthor.setModel(jListModelAuthor); // ......
// 代碼片段四,對左邊的JList進行遍歷,處理,處理結果顯示在右邊JTextArea,並刷左右界面顯示 ListModel<String> lm = jListAuthor.getModel(); int totalIndexs = lm.getSize();
// 起始值從當前選擇的記錄+1 for(int index=jListAuthor.getSelectedIndex()+1; index<totalIndexs; index++) { String uname = (String)lm.getElementAt(index);
// ...... // ......
// 刷新左邊JList窗口 jListAuthor.setSelectedIndex(index); jListAuthor.ensureIndexIsVisible(index);
// 如果左邊界面刷新出現問題,可以嘗試加入此條語句 jScrollPaneAuthor.repaint();
List<String> tempResult = myService.processRecord(uname); for(String str: tempResult) { // 右邊增加一行處理結果 jTextAreaInfo.append(str + "\n"); // 刷新右邊JTextArea窗口 jTextAreaInfo.setCaretPosition(jTextAreaInfo.getDocument().getLength());
// ...... // ...... } }
3. 效果