Node.JS
Node.JS

Reputation: 1570

JScrollPane is missing when I run the program

I'm trying to make a log file viewer that every 200ms sets the content of JTextarea to System.log But JScrollPane is missing when I run the program.

Thank you.

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 "";
        }
    }

Upvotes: 1

Views: 85

Answers (1)

rpax
rpax

Reputation: 4496

Add the text to the JScrollPane, and the JScrollPane to the Panel, instead of adding it twice

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

And then,

frame.getContentPane().add(panel)

Upvotes: 1

Related Questions