2014-03-04 83 views
1

我正在嘗試做一個日誌文件查看器,每200ms將JTextarea的內容設置爲System.log 但是當我運行程序時JScrollPane丟失。當我運行程序時JScrollPane丟失

謝謝。

enter image description here

import java.nio.ByteBuffer; 
import java.nio.charset.Charset; 
import java.nio.file.Files; 
import java.nio.file.Paths; 

private static void initializeInteractiveLog() { 
     JPanel panel = new JPanel(); 
     panel.setBorder(new TitledBorder(new EtchedBorder(), "Display Log Area")); 
     final JTextArea text = new JTextArea(16, 58); 
     text.setEditable(false); 
     JScrollPane scroll = new JScrollPane(text); 
     scroll.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); 
     panel.add(text); 
     panel.add(scroll); 
     JFrame frame = new JFrame(); 
     frame.add(panel); 
     frame.pack(); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
     Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
     frame.setLocation(dim.width/2 - frame.getSize().width/2, dim.height 
       /2 - frame.getSize().height/2); 
     frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); 

     new Timer().schedule(new TimerTask() { 
      public void run() { 
       if (Log.hasChanged) 
        text.setText(readFile("./src/System.log", 
          Charset.defaultCharset())); 
      } 
     }, 1, 200); 

    } 

private static String readFile(String path, Charset encoding) { 
     try { 
      byte[] encoded = Files.readAllBytes(Paths.get(path)); 
      return encoding.decode(ByteBuffer.wrap(encoded)).toString(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      return ""; 
     } 
    } 
+1

請張貼編譯碼。看到這個[鏈接](http://stackoverflow.com/help/mcve) – Reimeus

+0

@Reimeus當然,我剛剛得到了答案,但下次我會發布整個代碼。謝謝(你的)信息。 –

回答

1

的文本添加到JScrollPane中,和JScrollPane中的面板,而不是添加了兩次

JScrollPane scrollPane = new JScrollPane(text); 
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); 
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); 
panel.add(scrollPane) 

然後,

frame.getContentPane().add(panel) 
相關問題