运行程序时缺少JScrollPane

时间:2014-03-04 22:50:48

标签: java swing layout jpanel jscrollpane

我正在尝试创建一个日志文件查看器,每隔200ms将JTextarea的内容设置为System.log 但是当我运行程序时,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 个答案:

答案 0 :(得分:1)

将文本添加到JScrollPane,将JScrollPane添加到Panel,而不是将其添加两次

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

然后,

frame.getContentPane().add(panel)