【发布时间】:2013-07-07 06:52:45
【问题描述】:
我是 Java 新手,正在尝试制作一个与 MatLAB 的命令窗口完全一样的 GUI。
我正在尝试将当前在 JTextArea 中键入的行发送到控制台而不是整个 JTextArea。我目前的策略是使用 caretlistener 和 keylistener。现在我使用“matlab 的响应”作为占位符响应,当我按下回车时,它应该是该行下方的行。
这是我的代码:
public class MatlabGui extends JPanel implements KeyListener {
protected JTextArea myTextArea;;
public MatlabGui() {
super(new GridBagLayout());
myTextArea = new JTextArea(50, 75);
myTextArea.setEditable(true);
JScrollPane myScrollPane = new JScrollPane(myTextArea);
GridBagConstraints myCons = new GridBagConstraints();
myCons.gridwidth = GridBagConstraints.REMAINDER;
myCons.fill = GridBagConstraints.BOTH;
myCons.weightx = 1;
myCons.weighty = 1;
add(myScrollPane, myCons);
myTextArea.addKeyListener(this);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Matlab");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new MatlabGui());
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
@Override
public void keyPressed(KeyEvent evt) {
// TODO Auto-generated method stub
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
try {
myTextArea.addCaretListener(CaretListener);
int caretpos = myTextArea.getCaretPosition();
int start = 0;
int end = 0;
start = myTextArea.getLineStartOffset(caretpos);
end = myTextArea.getLineEndOffset(caretpos);
System.out.println(myTextArea.getText(start, end));
} catch (BadLocationException ex) {
System.out.println(ex.getMessage());
}
myTextArea.append("\n" + ">>>" + " " + "matlab's response");
}
}
public String getString() {
return myTextArea.getText();
}
@Override
public void keyReleased(KeyEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent arg0) {
// TODO Auto-generated method stub
}
}
非常感谢所有帮助。干杯
【问题讨论】:
-
当你说控制台时,你的意思是标准输出?另外,您不想将文本区域分成两部分吗?一个用于输出,一个用于用户输入?
-
是的,我的意思是标准输出;我想是这样。由于我的项目的要求,我不想将两者分开 - 我试图模仿不将两者分开的 matlab commmand 窗口。
-
为什么不使用简单的
JTextField,而且 KeyListerners 对于 Swing 来说是低级的......,使用它们不是一个好主意:-)
标签: java swing jtextarea keylistener caret