Я наконец пытаюсь перенести свои старые консольные программы на Swing, чтобы облегчить распространение среди моих друзей.С этой целью я пытаюсь написать класс 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());
}
}