【发布时间】:2019-11-21 23:26:56
【问题描述】:
我有一个简单的聊天框,其中包含以下代码:
public class Chatbox extends JFrame
{
JPanel mainPanel;
JTextArea inputField;
JTextArea chatTextArea;
JLabel chatLabel;
boolean typing;
Timer t;
public Chatbox()
{
createAndShowGUI();
}
private void createAndShowGUI()
{
// Set frame properties
setTitle("Plain Text Editor - <ID>");
setDefaultCloseOperation(EXIT_ON_CLOSE);
// Create a JPanel and set layout
mainPanel=new JPanel();
mainPanel.setLayout(new GridLayout(0,1));
// Create JTextField, add it.
inputField=new JTextArea();
//inputField.setWrapStyleWord(true);
inputField.setLineWrap(true);
JScrollPane sp = new JScrollPane(inputField, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
mainPanel.add(sp);
// Add panel to the south,
add(mainPanel,BorderLayout.SOUTH);
// Add a KeyListener
inputField.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent ke)
{
// If he presses enter, add text to chat textarea
if(ke.getKeyCode()==KeyEvent.VK_ENTER) showLabel(inputField.getText());
}
});
// Create a textarea
chatTextArea=new JTextArea();
// Make it non-editable
chatTextArea.setEditable(false);
// Set some margin, for the text
chatTextArea.setMargin(new Insets(7,7,7,7));
chatTextArea.setLineWrap(true);
chatTextArea.setWrapStyleWord(true);
// Set a scrollpane
JScrollPane js=new JScrollPane(chatTextArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
add(js);
addWindowListener(new WindowAdapter(){
public void windowOpened(WindowEvent we)
{
// Get the focus when window is opened
inputField.requestFocus();
}
});
setSize(400,400);
setLocationRelativeTo(null);
setVisible(true);
}
private void showLabel(String text)
{
// If text is empty return
if(text.trim().isEmpty()) return;
// Otherwise, append text with a new line
chatTextArea.append(text+"\n");
// Set textfield and label text to empty string
inputField.setText("");
}
}
但是,当我按 Enter 键进入 TextArea 时,会附加一个额外的空间。我怎样才能使消息被单独附加而没有额外的空白?
我也不确定 JScrollPane 是否弄乱了间距,因为在我实施 JScrollPane 之前没有发生此问题。
【问题讨论】:
-
inputField.addKeyListener是个坏主意,请改用ActionListener -
尝试反转
chatTextArea.append(text+"\n");以便新行作为文本的前缀