我是 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
}
}
非常感谢所有帮助。干杯