2014-03-04 57 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) 
相关问题