1
我正在嘗試做一個日誌文件查看器,每200ms將JTextarea的內容設置爲System.log 但是當我運行程序時JScrollPane丟失。當我運行程序時JScrollPane丟失
謝謝。
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 "";
}
}
請張貼編譯碼。看到這個[鏈接](http://stackoverflow.com/help/mcve) – Reimeus
@Reimeus當然,我剛剛得到了答案,但下次我會發布整個代碼。謝謝(你的)信息。 –