Java JTextArea - Adding a newline

后端 未结 4 1321
孤街浪徒
孤街浪徒 2021-01-28 08:00

So I\'m stumped. I, for some reason, seem to remember that Java does weird things when you try to add new lines to stuff... so I think that may be the problem here.

Thi

4条回答
  •  遥遥无期
    2021-01-28 08:25

    EDIT: After I see your full code, your keylistener is working. The problem is: outputArea.setText(txt); who overwrites your linebreaks. Try something like this:

    public void displayText(KeyEvent k){
        txt = inputArea.getText();
        char key = k.getKeyChar();
        if(key != KeyEvent.VK_ENTER)
            outputArea.append(Character.toString(k.getKeyChar()));
        else {
            // do something special, then add a linebreak
            outputArea.append("\n");
        }
    }
    

    ORIGINAL ANSWER: Try using getKeyChar() instead of getKeyCode(). See http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/KeyEvent.html for when to use what. Also, since you are just testing on enter, you probarly won't need to use a KeyListener. You can use a ActionListener on the input-field instead. See sample code for both ActionListener and KeyListener solutions below.

    public class JTextAreaTest extends JFrame{
    private JTextArea txaConsole;
    private JTextField txtInput;
    private JButton btnSubmit;
    
    public JTextAreaTest(){
        SubmitListener submitListener = new SubmitListener();
        MyKeyListener myKeyListener = new MyKeyListener();
    
        txaConsole = new JTextArea(10,40);
        txtInput = new JTextField();
        txtInput.addActionListener(submitListener);
        //txtInput.addKeyListener(myKeyListener);
        btnSubmit = new JButton("Add");
        btnSubmit.addActionListener(submitListener);
    
        add(new JScrollPane(txaConsole), BorderLayout.NORTH);
        add(txtInput, BorderLayout.CENTER);
        add(btnSubmit, BorderLayout.EAST);
    
    
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);
        txtInput.requestFocusInWindow();
    }
    
    private void addInputToConsole(){
        String input = txtInput.getText().trim();
        if(input.equals("")) return;
    
        txaConsole.append(input + "\n");
        txtInput.setText("");
    }
    
    // You don't need a keylistener to listen on enter-presses. Use a
    // actionlistener instead, as shown below.
    private class MyKeyListener extends KeyAdapter {
        @Override
        public void keyTyped(KeyEvent e) {
            if(e.getKeyChar() == KeyEvent.VK_ENTER)
                addInputToConsole();
        }
    }
    
    private class SubmitListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            addInputToConsole();
        }
    }
    
    public static void main(String[] args) {
        new JTextAreaTest();
    }
    }
    

提交回复
热议问题