How to preserve command prompt's formatting inside a jTextArea (or some other type of console)?

前端 未结 1 2174
孤独总比滥情好
孤独总比滥情好 2020-12-12 03:31

I cannot figure out how to preserve command prompt\'s formatting when I output the stream inside a Java program. Anyone have any suggestions?

相关标签:
1条回答
  • 2020-12-12 03:45

    There are a number of possible solutions available to you depending on how your data is derived...

    The most basic would be to ensure you are using a fixed width font...

    enter image description here

    import java.awt.BorderLayout;
    import java.awt.EventQueue;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class OutputTest {
    
        public static void main(String[] args) {
            new OutputTest();
        }
    
        public OutputTest() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            public TestPane() {
                String[] lines = {
                    "Idx     Met        MTU        State                Name           ",
                    "---  ---------  ----------  ------------  --------------------------",
                    "  1         50  4294967295  connected     Loopback Psudo-Interface 1",
                    " 11         10        1500  connected     Local Area Connection     ",
                    " 11          5        1500  disconnected  Local Area Connection 3   ",
                };
    
                setLayout(new BorderLayout());
                JTextArea ta = new JTextArea(10, 40);
                ta.setFont(new Font("Monospaced", Font.PLAIN, 13));
                for (String text : lines) {
                    ta.append(text + "\n");
                }
                add(new JScrollPane(ta));
            }
    
        }
    
    }
    

    This is great if your piping content from another source (like an external command).

    If you have control of the content, you could use String.format, but again, unless you're using a fixed width font, it won't make any difference, you will still have formatting issues.

    Another solution would be to use a html table in a JEditorPane, then the font doesn't matter

    Another solution might be to use a JTable which is designed to present data in a tabular form. See How to Use Tables for more details

    Updated

    It's a bug with the auto generated code in Netbeans 8.0 I'm pretty sure. It just made it tough to track down the issue.

    I doubt very highly that it's a bug, as this is been used by hundreds if not thousands of people every day...but without a runnable example which demonstrates your problem it's impossible to know for sure...

    ta.setFont(new Font("Monospaced", Font.PLAIN, 13)); BUT if you switch to bold or italics or bold italics then the line is generated and works correctly.

    I beg to differ...

    Fixed Width Font

    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.EventQueue;
    import java.awt.Font;
    import java.awt.GridLayout;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextArea;
    import javax.swing.UIManager;
    import javax.swing.UnsupportedLookAndFeelException;
    
    public class TestTable {
    
        public static void main(String[] args) {
            new TestTable();
        }
    
        public TestTable() {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }
    
                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
    
        public class TestPane extends JPanel {
    
            public TestPane() {
                setLayout(new GridLayout(4, -1));
                String[] lines = {
                    "Idx     Met        MTU        State                Name           ",
                    "---  ---------  ----------  ------------  --------------------------",
                    "  1         50  4294967295  connected     Loopback Psudo-Interface 1",
                    " 11         10        1500  connected     Local Area Connection     ",
                    " 11          5        1500  disconnected  Local Area Connection 3   ",};
    
                Font baseFont = new Font("Monospaced", Font.PLAIN, 13);
                addTextArea(baseFont, lines);
                addTextArea(baseFont.deriveFont(Font.ITALIC), lines);
                addTextArea(baseFont.deriveFont(Font.BOLD), lines);
                addTextArea(baseFont.deriveFont(Font.BOLD | Font.ITALIC), lines);
            }
    
            protected void addTextArea(Font font, String... lines) {
    
                JTextArea ta = new JTextArea(20, 40);
                ta.setFont(font);
                for (String text : lines) {
                    ta.append(text + "\n");
                }
                ta.setCaretPosition(0);
                add(new JScrollPane(ta));
            }
    
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(200, 200);
            }
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题