Java console show console

Creating a console in Java

When I try to use java.lang.System.console(), I get a null pointer. I can still write to out and read from in, but this only works when I run straight from my IDE. When I run the .jar file directly, nothing happens. How can I create a console like I’d see using std::cout for use in Java? Edit: I was hoping to just create one, rather than understand why I don’t have one, since I need one for my program’s operation.

5 Answers 5

Perhaps you’re trying to get the console by double-clicking in the jar

Try creating a batch file that opens the console for you.

You can however create a console using Swing and redirect standard input/output there.

How are you running the JAR file exactly? That would be the expected behavior for double-clicking its icon in Windows Explorer, as Kelly alluded to, but not for firing it up from the command line.

From the Console entry in the API (emphasis mine):

Whether a virtual machine has a console is dependent upon the underlying platform and also upon the manner in which the virtual machine is invoked. If the virtual machine is started from an interactive command line without redirecting the standard input and output streams then its console will exist and will typically be connected to the keyboard and display from which the virtual machine was launched. If the virtual machine is started automatically, for example by a background job scheduler, then it will typically not have a console.

Источник

How do I display the Java console?

I’m aware of the fact that you can set it to «show» in the Java control panel, but that’s not what I’m asking about. I’m curious about the other options. «Do not start» is pretty straightforward, but what about «Hide»? That would seem to imply that it is indeed running. If so, how can I make it show on demand from the hidden state? Reason: It’s annoying to have it open ALL the time, hoping there’s a way to (preferably via keystroke) bring it from «hidden» to «shown» state for occasional debugging.

2 Answers 2

To view the Java console, right click on the Java icon in the system tray (assuming you’re using Windows) and choose «Open console» — as pictured at the bottom of this page

Good to know. However, my Java icon doesn’t show up in the system tray. I see a Java control panel option «Place Java icon in system tray» under the «Miscellaneous» options. I’ve enabled that, but still don’t see a Java icon in my system tray.

Did you happen to know the Java icon only appears in the system tray after you launch an applet or WebStart app in your browser? If the program is launched from the Windows command line or via an executable, the icon won’t appear. If you are using Firefox, see if there is an «Open Java Console» option under the «Tools» menu. See also this discussion for possible ways to reset it.

The apps that I periodically need to have users pop a console to help in debugging are JNLP/web start apps, and it does not appear when they launch from the browser.

Источник

How do I make my java application open a console/terminal window?

Is there any way I can make an executable .jar that will open up the command line when double clicked? I’m making a text-based adventure game. As of right now it is just a maze with rooms. Eventually it is going to be much bigger and more in depth but for now I just want to get the basic structure down. Anyways, to make this work I’ve been getting output and input from the System.out.printf command and the java.util.Scanner. It’s all working beautifully so far but I’ve realized I’m going to run into a problem when I try to send this to other people that don’t know how or just don’t want to run the program from the command line.

13 Answers 13

I found this while looking for an answer myself, I ended up writing this bit:

/** * This opens a command line and runs some other class in the jar * @author Brandon Barajas */ import java.io.*; import java.awt.GraphicsEnvironment; import java.net.URISyntaxException; public class Main< public static void main (String [] args) throws IOException, InterruptedException, URISyntaxException< Console console = System.console(); if(console == null && !GraphicsEnvironment.isHeadless())< String filename = Main.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6); Runtime.getRuntime().exec(new String[]); >else < THEMAINCLASSNAMEGOESHERE.main(new String[0]); System.out.println("Program has ended, please type 'exit' to close the console"); >> > 

not sure if my answer is still relevant, but feel free to use it with the comment kept in o/

Читайте также:  Document

Only flaw I can think of is that it leaves the cmd window open after the program completes.

Usage: place this class in the same package as your main class and set it as the main class, it will open a command prompt window if one is not open, or if one is open launch the main class. Name / location of jar file is automatic. Designed for windows, but if you want it for another system just message me and I’ll fix it. (I could do OS detection but I’m lazy and just making this so I can turn in a double-click jar file to my professor who uses windows).

Writing at 2am, should clarify, I found this post while looking for an answer and saw none, so I wrote this.

It said «Error: Unable to access jarfile C:/660/efx/worskspace/. What’s the reason for that? Can you fix it?

@mk7 you probably forgot to replace «THEMAINCLASSNAMEGOESHERE» with the intended main class of your project, if not, give me the full error message.

Already replaced that one and another one two lines above. Error: «Unable to access jarfile C:/eclipse/workspace/TestConsole/bin/» I tried to switch to another workspace and it’s still the same error message on the cmd prompt window. I used Eclipse Mars and java sdk 1.8u60

Oh, I think I may know what’s going on now. Are you trying to run it using eclipses native environment? You need to compile it into a jar first (with this as the main class for compilation purposes), then the jar will be double-clickable (there is no need for a script like this inside eclipse, since it creates a terminal environment for you).

If you want full control, you can implement a Console window in Swing which does what you have now.

If you cannot open said window (if headless) or the user asks for it on the command line, then just default to your current behaviour.

I didn’t know much of anything about swing when I asked this question. After looking into it I managed to make something that didn’t have anything to do with a Scanner and instead uses a JTextArea and a JTextField to get input and output. It works very well so thank you for this answer.

What you mean by «Console window»? Are you talking about a window with a JTextArea that works like a console, or you are talking about an actual command line window like the cmd from Windows?

@carloswm85 A Swing window. I do not know if it is possible to open a command line window using Windows specific API calls.

Double-clicking a jar opens it with whatever application you’ve associated to it in your OS. By default, javaw[.exe] is normally associated to jar files. That’s the binary that runs without a terminal window. To see a terminal on double-click, you’d need to associate the java[.exe] binary with jar files.

Or you can provide a .sh .bat that will open a terminal and call your java in it.

As long as the .jar is executed with java.exe, a commandline window will always show up. executing it with javaw.exe would prevent this.

What does that mean java.exe vs javaw.exe? I’m just wanting the .jar to be double clicked. Sorry I’m still a bit new.

oh you mean the java commmand. that requires first going into the command line and running it that way. I was hoping there was a way to double click the .jar and have it then open a command line window. because most of my friends won’t know how to run the program in the command line and/or they don’t want to.

when you look into your Jre’s «bin» folder, you’ll see (among oithers) a java.exe and a javaw.exe. It depends on the System settings, which exe will be executed when doubleclicking an jar. Look at this question: stackoverflow.com/questions/394616/running-jar-file-in-windows

Читайте также:  Elements in html meaning

So this is my solution, I used the code from @Brandon Barajas and modified it. It creates a batchfile that starts the program by itself.

public static void main(String[] args) < Console console = System.console(); if(console == null && !GraphicsEnvironment.isHeadless()) < String filename = YOURMAINCALSS.class.getProtectionDomain().getCodeSource().getLocation().toString().substring(6); try < File batch = new File("Launcher.bat"); if(!batch.exists())< batch.createNewFile(); PrintWriter writer = new PrintWriter(batch); writer.println("@echo off"); writer.println("java -jar "+filename); writer.println("exit"); writer.flush(); >Runtime.getRuntime().exec("cmd /c start \"\" "+batch.getPath()); > catch(IOException e) < e.printStackTrace(); >> else < //your program code. >> 

If you want you can add a writer.println(«pause»); before the «exit» print, to keep the window open after the progam finishes. Then you need to hit ENTER to close the window.

You can use this program. This program creates a console for JAR programs (when JAR programs are run by double clicking on them).

import java.io.*; import javax.swing.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.text.*; import javax.swing.border.*; class InitComponents < public static JFrame setupJFrameAndGet(String title, int width, int height) < JFrame tmpJF = new JFrame(title); tmpJF.setSize(width, height); tmpJF.setLocationRelativeTo(null); tmpJF.setLayout(null); tmpJF.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); return tmpJF; >// end of setupJFrameAndGet public static JTextArea setupJTextAreaAndGet(String text, int rows, int columns, boolean setEditableFlag, boolean setLineWrapFlag, boolean setWrapStyleWordFlag, boolean setBoundsFlag, int xpos, int ypos, int width, int height) < JTextArea tmpJTA = new JTextArea(text, rows, columns); tmpJTA.setEditable(setEditableFlag); tmpJTA.setLineWrap(setLineWrapFlag); tmpJTA.setWrapStyleWord(setWrapStyleWordFlag); if (setBoundsFlag == true) < tmpJTA.setBounds(xpos, ypos, width, height); >return tmpJTA; > // end of setupJTextAreaAndGet public static JScrollPane setupScrollableJTextAreaAndGet(JTextArea jta, int xpos, int ypos, int width, int height) < JScrollPane tmpJSP = new JScrollPane(jta); tmpJSP.setBounds(xpos, ypos, width, height); return tmpJSP; >// end of setupScrollableJTextAreaAndGet public static JMenuBar setupJMenuBarAndGet() < JMenuBar tmpJMB = new JMenuBar(); return tmpJMB; >// end of setupJMenuBarAndGet public static JMenu setupJMenuAndGet(String text) < JMenu tmpJM = new JMenu(text); return tmpJM; >// end of setupJMenuAndGet public static JMenuItem setupJMenuItemAndGet(String text) < JMenuItem tmpJMI = new JMenuItem(text); return tmpJMI; >// end of setupJMenuItemAndGet >// end of InitComponents public class ConsoleForJARPrograms implements KeyListener, ActionListener < Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); int screenWidth = screenSize.width; int screenHeight = screenSize.height; String title = null; String text = null; JFrame jf = null; JTextArea jta = null; JScrollPane jsp = null; JMenuBar jmb = null; JMenu jm = null; JMenuItem jmi = null; int initialCaretPosition = 0; int currentCaretPosition = 0; boolean inputAvailable = false; // key codes int BACKSPACE = 8; int ENTER = 10; int PG_UP = 33; // do nothing for this key pressed int PG_DN = 34; // do nothing for this key pressed int END = 35; int HOME = 36; int LEFT_ARROW = 37; int UP_ARROW = 38; // do nothing for this key pressed //int RIGHT_ARROW = 39; // handled by JTextArea int DOWN_ARROW = 40; // do nothing for this key pressed int CTRL = 128; int A = 65; // disable ctrl-a int H = 72; // handle ctrl-h //int DELETE = 127; // handled by JTextArea public void actionPerformed(ActionEvent ae) < int cCurrPos = jta.getCaretPosition(); jta.selectAll(); jta.copy(); jta.select(cCurrPos, cCurrPos); >// end of actionPerformed public void keyTyped(KeyEvent ke) < >// end of keyTyped public void keyReleased(KeyEvent ke) < >// end of keyReleased public void keyPressed(KeyEvent ke) < int keyCode = ke.getKeyCode(); if ((keyCode == PG_UP) || (keyCode == PG_DN) || (keyCode == UP_ARROW) || (keyCode == DOWN_ARROW) || ((keyCode == A) && (ke.getModifiersEx() == CTRL))) < ke.consume(); >else if ((keyCode == LEFT_ARROW) || (keyCode == BACKSPACE) || ((keyCode == H) && (ke.getModifiersEx() == CTRL))) < synchronized(this) < if (jta.getCaretPosition() > // end of synchronized block > else if (keyCode == HOME) < synchronized(this) < jta.setCaretPosition(initialCaretPosition); ke.consume(); >// end of synchronized block > else if (keyCode == END) < synchronized(this) < jta.setCaretPosition(jta.getDocument().getLength()); ke.consume(); >// end of synchronized block > else if (keyCode == ENTER) < jta.setCaretPosition(jta.getDocument().getLength()); synchronized(this) < currentCaretPosition = jta.getCaretPosition(); // If character at initial caret position is newline then it means that the user has // pressed enter without enetring any other character. Also, the code gets called here // as soon as enter is pressed which means that the caret position (jta.getCaretPosition()) // of the document will be incremented by 1 by the system after this code returns. // This means that if at initial caret position, the character is newline, then we must ignore // this enter and increment initial caret position by 1 and do not set inputAvailable to true. try < String charAtInitialCaretPosition = jta.getText(initialCaretPosition, 1); if ((charAtInitialCaretPosition.equals("\n")) == true) < initialCaretPosition++; >> catch (Exception e) < >/* debug: start try < System.out.println("keyPressed (1): initial = " + initialCaretPosition + ", current = " + currentCaretPosition + ", System current = " + jta.getDocument().getLength()); String initialString = jta.getText(initialCaretPosition, 1); String currentString = jta.getText(currentCaretPosition, 1); System.out.println("char at initial = " + initialString + ", char at current = " + currentString); if ((initialString.equals("\n")) == true) < System.out.println("char at initial is newline"); >if ((currentString.equals("\n")) == true) < System.out.println("char at current is newline"); >> catch (Exception e) < >debug:end */ if ((currentCaretPosition - initialCaretPosition) > 0) < inputAvailable = true; notifyAll(); >> // end of synchronized block > // end of if else if > // end of keyPressed String getInputFromJTextArea(JTextArea jta) < int len = 0; String inputFromUser = ""; while (true) < synchronized(this) < if (inputAvailable == true) < len = currentCaretPosition - initialCaretPosition; try < inputFromUser = jta.getText(initialCaretPosition, len); initialCaretPosition = currentCaretPosition; >catch (Exception e) < inputFromUser = ""; return inputFromUser; >// end of outer try catch /* The following lines of code are not needed now. if ((len == 1) && (inputFromUser.equals("\n")) == true) < try < wait(); continue; >catch (Exception e) < >// end of try catch > else if (Character.compare(inputFromUser.charAt(0), '\n') == 0) < // matched // remove first character from inputFromUser inputFromUser = inputFromUser.substring(1); >*/ inputAvailable = false; return inputFromUser; > else < try < wait(); continue; >catch (Exception e) < >// end of try catch > // end of if else inputAvailable > // end of synchronized block > // end of while true > // end of getInoutFromJtextArea void outputToJTextArea(JTextArea jta, String text) < jta.append(text); jta.setCaretPosition(jta.getDocument().getLength()); synchronized(this) < initialCaretPosition = jta.getCaretPosition(); >> // end of outputToJTextArea void begin() < while (true) < outputToJTextArea(jta, "Enter some input (press enter after inputting): "); String input = getInputFromJTextArea(jta); outputToJTextArea(jta, "User input was: " + input + "\n\n"); >> // end of begin void configureJTextAreaForInputOutput(JTextArea jta) < jta.addKeyListener(this); // remove all mouse listeners for (MouseListener listener : jta.getMouseListeners()) < //outputToJTextArea(jta, "\nRemoving mouse listener\n"); jta.removeMouseListener(listener); >// remove all mouse motion listeners for (MouseMotionListener listener : jta.getMouseMotionListeners()) < //outputToJTextArea(jta, "\nRemoving mouse motion listener\n"); jta.removeMouseMotionListener(listener); >// remove all mouse wheel listeners for (MouseWheelListener listener : jta.getMouseWheelListeners()) < //outputToJTextArea(jta, "\nRemoving mouse wheel listener\n"); jta.removeMouseWheelListener(listener); >> // end of configureJTextAreaForInputOutput void createAndShowGUI() < title = "Console"; jf = InitComponents.setupJFrameAndGet(title, screenWidth - 150, screenHeight - 100); jta = InitComponents.setupJTextAreaAndGet("", 1000, 100, true, true, true, false, 0, 0, 0, 0); configureJTextAreaForInputOutput(jta); jsp = InitComponents.setupScrollableJTextAreaAndGet(jta, 10, 10, screenWidth - 180, screenHeight - 180); jsp.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED); jsp.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); jf.add(jsp); //jf.setLocation(screenWidth / 5, screenHeight / 6); jmb = InitComponents.setupJMenuBarAndGet(); jm = InitComponents.setupJMenuAndGet("Copy All to Clipboard"); jm.setBorder(BorderFactory.createLineBorder(Color.green, 2)); jmi = InitComponents.setupJMenuItemAndGet("Copy All to Clipboard"); jm.add(jmi); jmb.add(jm); jmi.addActionListener(this); jf.setJMenuBar(jmb); jf.setVisible(true); >// end of createAndShowGUI public static void main(String[] args) < ConsoleForJARPrograms cfjp = new ConsoleForJARPrograms(); cfjp.createAndShowGUI(); cfjp.begin(); >// end of main > // end of ConsoleForJARPrograms 

Источник

Читайте также:  Out argument in java

How to show command executing in the console and access its output in java

I have a command line tool that queries a server and prints the status of pending jobs to run. This can take up to 30 seconds. I need to call this tool from java and I want to show its output in a text area on my GUI. For the purposes of example, lets say the command is «dir» in windows. Process.getRuntime().exec(«cmd /c dir»); blocks until the command finishes executing, so I thought it would be best to show the command executing in the terminal, then read the output and show it in my text area for future reference. However, the console is hidden giving the user the impression that the application has stopped working. After much research, I have tried: cmd /k dir — runs in the background and can read output, but application hangs as it requires the /k switch means to keep the window open, but I can’t see it to close it. cmd /c start dir — opens in a new visible terminal, runs but doesn’t close. Closing manually doesn’t allow me to read the output cmd /k start dir — same result as above My question is, how can I spawn a command to run, see it running, and access its output?

Runtime.exec should not block until the command is finished, just until it is started and your process gets some processor time again.

It does in my scenario. It wont go to the next line in the code until the command specified in exec finishes running. is there a way I can access the output as it is written? I don’t think so. it is an external process — it must finish executing before control is returned to the Java app to read the output. Being able to read the output as it is written would be great!!

exec() doesn’t block. You can read and write to the external process. If it blocked, it would be almost useless.

Источник

Оцените статью