Java JTextArea - 添加换行符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1870630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java JTextArea - Adding a newline
提问by Pandemic21
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.
所以我很难过。出于某种原因,我似乎记得当您尝试向内容添加新行时 Java 会做一些奇怪的事情……所以我认为这可能是这里的问题。
This code is not working how you'd expect it to:
此代码无法按照您的预期工作:
public void displayText(KeyEvent k){
txt = inputArea.getText();
outputArea.setText(txt);
if(k.getKeyCode() == 10) //return
outputArea.setText(txt + "\n");
}
You can double-check to see if I have the getKeyCode() set to the right number, but I'm almost positive that that part is correct.
您可以仔细检查我是否将 getKeyCode() 设置为正确的数字,但我几乎肯定那部分是正确的。
EDIT: Thanks; I forgot about those constants...
编辑:谢谢;我忘记了那些常数...
And unfortunately, it works - but not really. if(k.getKeyCode() == k.VK_ENTER)
returns true (this is a fact), but "\n" does not create the newline.
不幸的是,它有效 - 但不是真的。if(k.getKeyCode() == k.VK_ENTER)
返回 true(这是事实),但 "\n" 不会创建换行符。
EDIT (take two): Full code:
编辑(取两个):完整代码:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUI extends JFrame implements KeyListener{
private JFrame frame;
private JTextField inputArea;
private JTextArea outputArea;
private String txt;
public GUI(){
frame = new JFrame("My Frame");
inputArea = new JTextField(1);
outputArea = new JTextArea(5,10);
inputArea.addKeyListener(this);
outputArea.setLineWrap(true);
txt = "";
frame.setLayout(new GridLayout(2,10));
frame.add(inputArea);
frame.add(outputArea);
frame.setVisible(true);
frame.pack();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void keyPressed(KeyEvent k){}
public void keyTyped(KeyEvent k){}
public void keyReleased(KeyEvent k) {
displayText(k);
}
public void displayText(KeyEvent k){
txt = inputArea.getText();
outputArea.setText(txt);
if(k.getKeyCode() == KeyEvent.VK_ENTER)
outputArea.append("\n");
//outputArea.setText(txt + "\n");
}
}
Then another class with the main:
然后是另一个主要的类:
public class Driver {
public static void main(String[] args){
GUI gui = new GUI();
}
}
EDIT: Basically, I'm trying to emulate Google Wave's ability to send text before the user presses Enter.
编辑:基本上,我试图模拟 Google Wave 在用户按下 Enter 之前发送文本的能力。
回答by Jacob Schoen
I know there is a difference with new line characters between OS's out there. You could try
我知道操作系统之间的换行符有所不同。你可以试试
System.getProperty("line.separator")
to get the new line character for the specific os it is running on. Don't know if that will fix your problem or not.
获取它正在运行的特定操作系统的新行字符。不知道这是否会解决您的问题。
回答by JasCav
EDIT
编辑
I have created a quick piece of code to add a KeyListener onto a JTextArea and this works fine. You don't need to particularly watch for an Enter key being pressed. How is this different from the rest of your code? (If you could paste more of it, that would be helpful.) I sort of feel like your KeyListener is not doing something properly. Are letters typing when you type? Try just taking out the if statement where you check for ENTER and see if that helps.
我创建了一段快速的代码来将 KeyListener 添加到 JTextArea 上,这很好用。您不需要特别注意按下 Enter 键。这与您的其他代码有何不同?(如果您可以粘贴更多内容,那会很有帮助。)我有点觉得您的 KeyListener 没有正确执行某些操作。打字的时候打字吗?尝试取出检查 ENTER 的 if 语句,看看是否有帮助。
public class TestGui {
private JFrame frame;
private JTextArea textArea;
public TestGui() {
frame = new JFrame();
frame.setSize(200, 200);
textArea = new JTextArea();
textArea.setSize(200, 200);
frame.add(textArea);
// Notice that I don't do anything inside this listener.
// It doesn't need to be here.
textArea.addKeyListener(new KeyListener() {
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyTyped(KeyEvent e) {
}
});
frame.setVisible(true);
}
public static void main(String[] args) {
TestGui gui = new TestGui();
}
}
回答by Mads Mob?k
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:
编辑:在我看到您的完整代码后,您的密钥侦听器正在工作。问题是:outputArea.setText(txt);
谁覆盖了你的换行符。尝试这样的事情:
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.htmlfor 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.
原始答案:尝试使用 getKeyChar() 而不是 getKeyCode()。请参阅http://java.sun.com/j2se/1.5.0/docs/api/java/awt/event/KeyEvent.html了解何时使用什么。此外,由于您只是在输入时进行测试,因此您可能不需要使用 KeyListener。您可以改为在输入字段上使用 ActionListener 。请参阅下面的 ActionListener 和 KeyListener 解决方案的示例代码。
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();
}
}
回答by camickr
I'm not sure I understand what you are trying to do, all I know is that you are using the wrong approach. You should NOT be using a KeyListener.
我不确定我是否理解您要做什么,我所知道的是您使用了错误的方法。您不应该使用 KeyListener。
From what I can see you want the contents of the output text area to be the same as the contents of the input area. If this is your requirement then you just use:
从我所见,您希望输出文本区域的内容与输入区域的内容相同。如果这是您的要求,那么您只需使用:
JTextArea input = new JTextArea(...);
JTextArea output = new JTextArea(...);
output.setDocument( input.getDocument() );
Or if you are trying to listen for all the changes to the input text area then you should be using a DocumentListener. The Swing tutorial has a section titled "How to Write a Document Listener" for more information.
或者,如果您正在尝试侦听输入文本区域的所有更改,那么您应该使用 DocumentListener。Swing 教程有一个标题为“如何编写文档侦听器”的部分以获取更多信息。