2009-08-10 9 views
9

Ho una domanda insolita: come posso creare una "console di comando" utilizzando Swing?Creazione di una console "Comando"

Quello che voglio avere è una console in cui gli utenti digitano i comandi, premere invio, e l'output del comando viene visualizzato sotto. Non voglio consentire all'utente di modificare il "prompt" e l'output precedente. Sto pensando a qualcosa come Windows CMD.EXE.

Ho dato un'occhiata alla domanda this, tuttavia non risponde alla mia domanda.

+0

Intendi qualcosa come l'area di lavoro BeanShell? – Kryten

+0

Perché dovresti usare Swing? Cosa c'è che non va con la semplice creazione di un'app console Java direttamente? – Juliet

+0

Questa è una risposta migliore di quella a cui stavo pensando. :-) – Jay

risposta

0

È possibile eseguire comandi arbitrari con Plesso utilizzando Commandline. Gestisce l'escaping degli argomenti, l'esecuzione specifica dell'ambiente e consente di associare i consumatori a stdout e stderr, lasciando all'utente il compito di concentrarsi sulla gestione.

Ecco un collegamento a another answe r ho dato, mostrando come è possibile impostare una Commandline e gestire l'output.

2

Se ho compreso correttamente la tua domanda, stai cercando di eseguire comandi specifici per la tua applicazione. Il mio consiglio sarebbe, se questo è il caso, di utilizzare due textareas, una che è una singola riga e una che occupa il resto dello spazio. Aggiungi alcuni gestori di eventi keypress a quello piccolo, che potrebbe essere modificato e rendere l'altro di sola lettura. Se è necessario disporre di un'area di testo singola, è possibile renderla di sola lettura e quindi aggiungere alcuni gestori di tasti per gestire i caratteri immessi e i tasti su/giù.

Spero di aver capito correttamente la tua domanda, buona fortuna.

0

Non vorrei provare le scorciatoie (come groovy/beanshell) a meno che non corrispondano esattamente alle vostre esigenze. Cercando di fare uno strumento di alto livello fai quello che vuoi quando non è quello che già fa può essere la cosa più frustrante della programmazione.

Dovrebbe essere abbastanza facile prendere un'area di testo e "Falla da sola", ma sarebbe molto più facile da fare come suggerito da qualcun altro e utilizzare un controllo di testo a una riga combinato con un'area di visualizzazione a più righe .

In entrambi i casi si desidera mantenere un controllo piuttosto preciso sull'intero sistema, intercettare e filtrare alcune sequenze di tasti, disabilitare l'input nell'area "Display" se si decide di farlo, forzare un clic sull'area di visualizzazione per inviare concentrarsi sul campo di input, ...

Se si esegue la casella singola, è necessario assicurarsi che l'input sia sempre nella parte inferiore della finestra e che si controlli il posizionamento del cursore (probabilmente non si li voglio in grado di fare qualsiasi input su qualsiasi linea tranne l'ultima riga).

Ti suggerisco di non assumere che un singolo controllo funzioni solo senza modifiche, aspetti di fare il lavoro di gambe e tutto andrà bene.

1

provare questo codice:

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); 
} 

Esso utilizza un JPanel come il pannello e un JLabel come la console. I comandi vengono passati a un oggetto CommandListener e il valore restituito viene stampato sulla console.

8

BeanShell fornisce un JConsole, una console di input a riga di comando con le seguenti caratteristiche:

  • un cursore lampeggiante
  • cronologia dei comandi
  • taglia/copia/incolla tra cui la selezione con i tasti freccia CTRL +
  • completamento comando
  • Immissione carattere Unicode
  • output testo colorato
  • ... e tutto viene racchiuso in un riquadro di scorrimento.

Il BeanShell JAR sono disponibili presso http://www.beanshell.org/download.html e la sorgente è disponibile via SVN da svn co http://ikayzo.org/svn/beanshell

Per maggiori informazioni su JConsole vedere http://www.beanshell.org/manual/jconsole.html

Ecco un esempio di utilizzo JConsole di BeanShell nell'applicazione:

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 restituisce ";" se premi Invio da solo.

+0

Questo non funziona per me. Sto usando 'bsh-2.0b4.jar'. Digitando 'quit' e premendo enter non fa altro che portare il cursore sulla nuova riga. Il colore di sfondo è bianco. I colori delle lettere sono neri. Non vedo mai 'Hai digitato:'. –

0

Se volete

qualcosa come Windows cmd.exe.

utilizzare cmd.exe. Tutto ciò che si stampa usando System.out.println("") verrà visualizzato lì. Quello che devi fare è creare un file .bat in cui si trova il tuo file compilato.

echo off 
cls 
java -jar fileName.jar 
Problemi correlati