为输入和输出创建Canvas - Java

时间:2015-11-11 18:41:22

标签: java user-interface

我想为输入和输出文本创建一个黑色画布。我想知道如何初始化和实现此代码。谢谢!

1 个答案:

答案 0 :(得分:2)

扩展user3437460所说的是你可以创建一个JFrame并将JTextArea添加到该JFrame。就像他说的那样,设置JTextArea的背景和前景颜色,并处理用户输入的任何输入。如果你还是不明白,这里有一个简单的例子:

public class Console extends JFrame
{
    private final JTextArea text;

    private final DocumentListener docListener = new DocumentListener()
    {
        @Override
        public void insertUpdate(DocumentEvent e)
        {
            System.out.println("String inserted");
            // This is called when text is inserted into the JTextArea
            // Similar to a user typing
        }

        @Override
        public void removeUpdate(DocumentEvent e)
        {
            System.out.println("String removed");
            // This is called when text is removed from the JTextArea
            // Similar to a user backspacing
        }

        @Override
        public void changedUpdate(DocumentEvent e)
        {
            // This isn't all that necessary because it doesn't apply to JTextAreas
        }
    };

    public Console()
    {
        text = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Console");

        text.setBackground(new java.awt.Color(0, 0, 0));
        text.setColumns(40);
        text.setForeground(new java.awt.Color(0, 255, 0));
        text.setRows(10);
        text.setText("I am a console!");
        text.setCaretColor(new java.awt.Color(0, 255, 0));
        Document doc = new PlainDocument();
        doc.addDocumentListener(docListener);
        text.setDocument(doc);
        getContentPane().add(new JScrollPane(text), java.awt.BorderLayout.CENTER);

        pack();
        setLocationRelativeTo(null);
    }                       

    public static void main(String args[])
    {
        EventQueue.invokeLater(new Runnable()
        {
            @Override
            public void run()
            {
                new Console().setVisible(true);
            }
        });
    }
}

我相信这是你想要实现的目标吗?