我终于尝试将旧的控制台程序迁移到 Swing,以便更轻松地分发给我的 friend 。为此,我尝试编写一个可以扩展的 ConsoleFrame 类,而不是 JFrame,这将允许我尽可能轻松地将旧代码与 Swing 连接。 out(String) 似乎有效,但 inln() 让我难住了。
//Imports not included
public class ConsoleFrame extends JFrame
{
protected JTextField in;
protected JTextArea out;
public ConsoleFrame(){
this("Console Frame", 80, 10);
}
public ConsoleFrame(int cols){
this("Console Frame", cols, 10);
}
public ConsoleFrame(int cols, int rows){
this("Console Frame", cols, rows);
}
public ConsoleFrame(String title){
this(title, 80, 10);
}
public ConsoleFrame(String title, int cols, int rows){
in = new JTextField();
in.setEditable(true);
in.setColumns(cols);
out = new JTextArea();
out.setEditable(false);
out.setColumns(cols);
out.setRows(rows);
out.setWrapStyleWord(true);
setTitle(title);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
add(in, BorderLayout.PAGE_END);
add(out, BorderLayout.PAGE_START);
pack();
}
protected void out(String o) {
out.append(o);
}
protected void outln(String o) {
out(o + BIO.$ln); //BIO.$ln == System.getProperty("line.separator")
}
/*
* This is supposed to halt execution until the user presses enter, then return the text entered in the JTextField named in.
*/
protected String inln() {
in.setEnabled(true);
KeyListener enter = new KeyListener() {
@Override
public void keyTyped(KeyEvent paramKeyEvent) {
if(paramKeyEvent.getKeyCode() == KeyEvent.VK_ENTER) {
if(in.hasFocus()) {
in.setEnabled(false);
}
}
}
@Override public void keyPressed(KeyEvent paramKeyEvent) {}
@Override public void keyReleased(KeyEvent paramKeyEvent) {}
};
in.addKeyListener(enter);
while(true){ //This loop is intended to interrupt flow until in.isEnabled()==false, which will only happen when the enter key is typed.
if(in.isEnabled()==false){
String result = in.getText();
in.setText("");
in.setCaretPosition(0);
this.removeKeyListener(enter);
in.setEnabled(true);
return result;
}
}
}
}
测试程序:
public class Tester extends ConsoleFrame
{
public static void main(String[] args) {
new Tester();
}
public Tester() {
super("Test", 60, 30);
out(inln());
}
}
最佳答案
不知道它是否能解决您的问题,但您不应该使用 KeyListner。
JTextField 被设计为使用 ActionListener 来处理 Enter 键。
关于java - 一名 Java 学徒尝试从 System.out.println 迁移到 swing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8261188/