2009-08-10 10 views
9

Tengo una pregunta un tanto inusual: ¿cómo puedo crear una "consola de comandos" usando Swing?Crear una consola de "comando"

Lo que quiero tener es una consola donde los usuarios escriben los comandos, presionen enter, y la salida del comando se muestra debajo. No quiero permitir que el usuario cambie la salida "prompt" y anterior. Estoy pensando en algo como Windows CMD.EXE.

He echado un vistazo a la pregunta this, sin embargo, no responde mi pregunta.

+0

¿Se refiere a algo así como el BeanShell Workspace? – Kryten

+0

¿Por qué usaría Swing? ¿Qué hay de malo con solo crear una aplicación de consola Java directamente? – Juliet

+0

Esta es una respuesta mejor que la que estaba pensando. :-) – Jay

Respuesta

0

Puede ejecutar comandos arbitrarios con Plexus usando la línea de comandos. Maneja el escape de los argumentos, la ejecución específica del entorno y le permite vincular a los consumidores con stdout y stderr, dejándote enfocado en el manejo.

Aquí hay un enlace a another answe que di, que muestra cómo puede configurar una línea de comando y manejar la salida.

2

Si entiendo su pregunta correctamente, está buscando ejecutar comandos específicos para su aplicación. Mi consejo sería, si este es el caso, utilizar dos áreas de texto, una que sea una línea y otra que ocupe el resto del espacio. Agregue algunos controladores de eventos de pulsación de tecla al pequeño, que sería editable, y haga que el otro sea de solo lectura. Si debe tener un área de texto única, puede hacer que sea de solo lectura y luego agregar algunos manejadores de tecla para manejar la entrada de caracteres y presionar las teclas arriba/abajo.

Espero haber entendido su pregunta correctamente, la mejor de las suertes.

0

No probaré los accesos directos (como groovy/beanshell) a menos que se ajusten exactamente a sus necesidades. Tratar de hacer que una herramienta de alto nivel haga lo que quiera cuando no es lo que ya hace puede ser lo más frustrante de la programación.

Debería ser bastante fácil tomar un área de texto y "Hacerla suya", pero sería mucho más fácil hacer lo que alguien sugirió y usar un control de texto de una línea combinado con un área de visualización de varias líneas .

En cualquiera de los casos, usted quiere mantener un control muy cerrado de todo el sistema, interceptar y filtrar algunas teclas, deshabilitar la entrada al área "Pantalla" si decide hacerlo, forzar un clic en su área de visualización para enviar centrarse en su campo de entrada, ...

Si hace una sola caja, querrá asegurarse de que su entrada esté siempre en la parte inferior de la caja y que controle el posicionamiento de su cursor (es probable que no lo haga) t quiero que puedan hacer cualquier entrada a cualquier línea, excepto la última línea).

Sugiero que no suponga que un solo control va a funcionar sin modificaciones, espere hacer el trabajo preliminar y todo estará bien.

1

probar este código:

import javax.swing.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 

/** 
* 
* @author Alistair 
*/ 
public class Console extends JPanel implements KeyListener { 

    private static final long serialVersionUID = -4538532229007904362L; 
    private JLabel keyLabel; 
    private String prompt = ""; 
    public boolean ReadOnly = false; 
    private ConsoleVector vec = new ConsoleVector(); 
    private ConsoleListener con = null; 
    private String oldTxt = ""; 
    private Vector history = new Vector(); 
    private int history_index = -1; 
    private boolean history_mode = false; 

    public Console() { 
     super(); 
     setSize(300, 200); 
     setLayout(new FlowLayout(FlowLayout.CENTER)); 
     keyLabel = new JLabel(""); 
     setFocusable(true); 
     keyLabel.setFocusable(true); 
     keyLabel.addKeyListener(this); 
     addKeyListener(this); 
     add(keyLabel); 
     setVisible(true); 
    } 

    public void registerConsoleListener(ConsoleListener c) { 
     this.con = c; 
    } 

    public String getPrompt() { 
     return this.prompt; 
    } 

    public void setPrompt(String s) { 
     this.prompt = s; 
    } 

    private void backspace() { 
     if (!this.vec.isEmpty()) { 
      this.vec.remove(this.vec.size() - 1); 
      this.print(); 
     } 
    } 

    @SuppressWarnings("unchecked") 
    private void enter() { 
     String com = this.vec.toString(); 
     String return$ = ""; 
     if (this.con != null) { 
      return$ = this.con.receiveCommand(com); 
     } 

     this.history.add(com); 
     this.vec.clear(); 
     if (!return$.equals("")) { 
      return$ = return$ + "<br>"; 
     } 
     // <HTML> </HTML> 
     String h = this.keyLabel.getText().substring(6, this.keyLabel.getText().length() - 7); 
     this.oldTxt = h.substring(0, h.length() - 1) + "<BR>" + return$; 
     this.keyLabel.setText("<HTML>" + this.oldTxt + this.prompt + "_</HTML>"); 
    } 

    private void print() { 
     this.keyLabel.setText("<HTML>" + this.oldTxt + this.prompt + this.vec.toString() + "_</HTML>"); 
     this.repaint(); 
    } 

    @SuppressWarnings("unchecked") 
    private void print(String s) { 
     this.vec.add(s); 
     this.print(); 
    } 

    @Override 
    public void keyTyped(KeyEvent e) { 
    } 

    @Override 
    public void keyPressed(KeyEvent e) { 
    } 

    @Override 
    public void keyReleased(KeyEvent e) { 
     this.handleKey(e); 
    } 

    private void history(int dir) { 
     if (this.history.isEmpty()) { 
      return; 
     } 
     if (dir == 1) { 
      this.history_mode = true; 
      this.history_index++; 
      if (this.history_index > this.history.size() - 1) { 
       this.history_index = 0; 
      } 
      // System.out.println(this.history_index); 
      this.vec.clear(); 
      String p = (String) this.history.get(this.history_index); 
      this.vec.fromString(p.split("")); 

     } else if (dir == 2) { 
      this.history_index--; 
      if (this.history_index < 0) { 
       this.history_index = this.history.size() - 1; 
      } 
      // System.out.println(this.history_index); 
      this.vec.clear(); 
      String p = (String) this.history.get(this.history_index); 
      this.vec.fromString(p.split("")); 
     } 

     print(); 
    } 

    private void handleKey(KeyEvent e) { 

     if (!this.ReadOnly) { 
      if (e.getKeyCode() == 38 | e.getKeyCode() == 40) { 
       if (e.getKeyCode() == 38) { 
        history(1); 
       } else if (e.getKeyCode() == 40 & this.history_mode != false) { 
        history(2); 
       } 
      } else { 
       this.history_index = -1; 
       this.history_mode = false; 
       if (e.getKeyCode() == 13 | e.getKeyCode() == 10) { 
        enter(); 
       } else if (e.getKeyCode() == 8) { 
        this.backspace(); 
       } else { 
        if (e.getKeyChar() != KeyEvent.CHAR_UNDEFINED) { 
         this.print(String.valueOf(e.getKeyChar())); 
        } 
       } 
      } 
     } 
    } 
} 


class ConsoleVector extends Vector { 

    private static final long serialVersionUID = -5527403654365278223L; 

    @SuppressWarnings("unchecked") 
    public void fromString(String[] p) { 
     for (int i = 0; i < p.length; i++) { 
      this.add(p[i]); 
     } 
    } 

    public ConsoleVector() { 
     super(); 
    } 

    @Override 
    public String toString() { 
     StringBuffer s = new StringBuffer(); 
     for (int i = 0; i < this.size(); i++) { 
      s.append(this.get(i)); 
     } 
     return s.toString(); 
    } 
} 

public interface ConsoleListener { 
    public String receiveCommand(String command); 
} 

Utiliza un JPanel que el panel y un JLabel que la consola. Los comandos se pasan a un objeto CommandListener y el valor devuelto se imprime en la consola.

8

BeanShell proporciona un JConsole, una consola de entrada de línea de comandos con las siguientes características:

  • un cursor parpadeante
  • historial de comandos
  • cortar/copiar/pegar incluyendo la selección con las teclas de flecha Ctrl +
  • finalización del comando
  • entrada de caracteres Unicode
  • texto de color salida
  • ... y todo viene envuelto en un panel de desplazamiento.
  • JAR

El BeanShell están disponibles en http://www.beanshell.org/download.html y la fuente está disponible a través de SVN de svn co http://ikayzo.org/svn/beanshell

Para obtener más información sobre JConsole ver http://www.beanshell.org/manual/jconsole.html

Aquí se muestra un ejemplo de la utilización de JConsole de BeanShell en su aplicación:

import java.awt.Color; 
import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.Reader; 

import javax.swing.JFrame; 

import bsh.util.GUIConsoleInterface; 
import bsh.util.JConsole; 

/** 
* Example of using the BeanShell project's JConsole in 
* your own application. 
* 
* JConsole is a command line input console that has support 
* for command history, cut/copy/paste, a blinking cursor, 
* command completion, Unicode character input, coloured text 
* output and comes wrapped in a scroll pane. 
* 
* For more info, see http://www.beanshell.org/manual/jconsole.html 
* 
* @author tukushan 
*/ 
public class JConsoleExample { 

    public static void main(String[] args) { 

     //define a frame and add a console to it 
     JFrame frame = new JFrame("JConsole example"); 

     JConsole console = new JConsole(); 

     frame.getContentPane().add(console); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.setSize(600,400); 

     frame.setVisible(true); 

     inputLoop(console, "JCE (type 'quit' to exit): "); 

     System.exit(0); 
    } 

    /** 
    * Print prompt and echos commands entered via the JConsole 
    * 
    * @param console a GUIConsoleInterface which in addition to 
    *   basic input and output also provides coloured text 
    *   output and name completion 
    * @param prompt text to display before each input line 
    */ 
    private static void inputLoop(GUIConsoleInterface console, String prompt) { 
     Reader input = console.getIn(); 
     BufferedReader bufInput = new BufferedReader(input); 

     String newline = System.getProperty("line.separator"); 

     console.print(prompt, Color.BLUE); 

     String line; 
     try { 
      while ((line = bufInput.readLine()) != null) { 
       console.print("You typed: " + line + newline, Color.ORANGE); 

       // try to sync up the console 
       //System.out.flush(); 
       //System.err.flush(); 
       //Thread.yield(); // this helps a little 

       if (line.equals("quit")) break; 
       console.print(prompt, Color.BLUE); 
      } 
      bufInput.close(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

    } 
} 

NB: JConsole returns ";" si presionas Enter por sí mismo.

+0

Esto no funciona para mí. Estoy usando 'bsh-2.0b4.jar'. Teclear 'quit' y presionar enter no hace más que traer el cursor a la nueva línea. El color de fondo es blanco. Los colores de las letras son negros. Nunca veo 'Escribiste:'. –

0

Si desea

algo como Windows cmd.exe.

uso cmd.exe. Todo lo que imprima usando System.out.println("") aparecerá allí. Lo que tienes que hacer es crear un archivo .bat donde está tu archivo compilado.

echo off 
cls 
java -jar fileName.jar 
Cuestiones relacionadas