這是我的問題我得到我的System.in重定向到JTextField。現在用戶可以按回車,它會發送我的文本。但是我的客戶端將無法訪問此JTextfield,所以我想知道是否可以在我的代碼中重新創建Enter鍵。是否有可能在JTextfield上拋出KeyEvent虛擬機?
public static JTextField jtfEntree = new JTextField();
public static TexfFieldStreamer ts = new TexfFieldStreamer(jtfEntree);
System.setIn(ts);
jtfEntree.addActionListener(ts);
//************************************************************************
private void commandLaunch(String command)
//************************************************************************
{
jtfEntree.setText(command);
//here is where i want to fire the key Enter
}
//************************************************************************
class TexfFieldStreamer extends InputStream implements ActionListener{
private JTextField tf;
private String str = null;
private int pos = 0;
public TexfFieldStreamer(JTextField jtf) {
tf = jtf;
}
public int read() {
//test if the available input has reached its end
//and the EOS should be returned
if(str != null && pos == str.length()){
str =null;
//this is supposed to return -1 on "end of stream"
//but I'm having a hard time locating the constant
return java.io.StreamTokenizer.TT_EOF;
}
//no input available, block until more is available because that's
//the behavior specified in the Javadocs
while (str == null || pos >= str.length()) {
try {
//according to the docs read() should block until new input is available
synchronized (this) {
this.wait();
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
//read an additional character, return it and increment the index
return str.charAt(pos++);
}
public void actionPerformed(ActionEvent arg0)
{
// TODO Auto-generated method stub
str = tf.getText() + "\n";
pos = 0;
synchronized (this) {
//maybe this should only notify() as multiple threads may
//be waiting for input and they would now race for input
this.notify();
}
}
}
如果您需要更多信息請在評論中留言! 感謝您的幫助
P.S .:我嘗試將操作偵聽器更改爲文檔偵聽器,但它並不總是觸發事件,因此它沒有像我想要的那樣動作。
試圖與機器人,但它似乎是一個文本框心不是越來越專注所以關鍵是剛剛按下後沒有出現
//************************************************************************
protected static void commandExecute(String Command) //COMMAND EXECUTE
//************************************************************************
{
jtfEntree.setText(Command);
jtfEntree.requestFocus();
Robot robot;
try {
robot = new Robot();
robot.keyPress(KeyEvent.VK_ENTER);
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jtfEntree.setText("");
}
//************************************************************************
*「我的客戶將無法訪問此JTextfield」*爲什麼不?和你最後的問題一樣,它將支付描述最終目標「提供基於命令行的工具來從遠程服務器獲取匯率」*。因爲它是,你的問題聽起來像*「我怎麼用螺絲起子安裝釘子?」* –