In Java, what is the best way to capture a <tab> keystroke?
Asked Answered
B

3

5

I'm having trouble capturing the <tab> keystroke in my Java command-line application. Using System.in.read() I don't seem to get anything when hitting the tab key. What is the best way to approach this?

To give some context, I'm trying to allow a user to hit the tab key mid-command to have it autocomplete the command (much like you might do in a bash shell). I'm open to suggestions if there are better approaches to achieving this (perhaps using System.in.read() isn't the best angle to approach this?).

Bitthia answered 5/1, 2011 at 20:27 Comment(1)
See stackoverflow.com/questions/1066318 for a discussion of reading a single character in 'raw mode'. As Paul and Michael have indicated, this is going to require a platform-dependent solution.Rearrange
T
7

Have a look at JLine. I have not used it myself. It uses a windows DLL (using JNI) and it has linux support to switch the console to character/raw mode instead of buffered mode. I have never used this before so use at your own risk. I am also not 100% sure if it will address your issue, but its worth a shot :)

EDIT: I can confirm it does work

ConsoleReader cr = new ConsoleReader();
while (cr.readVirtualKey() != 0x09){
  //loop till Tab is pressed
}

EDIT AGAIN: The library does contain autocomplete (by pressing tab) for the command line... Enjoy :)

Tymes answered 5/1, 2011 at 20:52 Comment(0)
U
1

Data from an InputStream is only made available when the user has pressed enter. I think you'll find that if you press enter after tab, the tab will show up.

In c applications, there is something similar: a shell sets the input mode to raw from cooked, since it needs the raw keystrokes. Readline is the normal library used for this in Linux. I'm not sure what's common on Windows. As far as I can think, something using JNI is the only option here.

Umpire answered 5/1, 2011 at 20:37 Comment(0)
H
0

I would guess that your shell is capturing tab and preventing it from getting to your application. There may not be anything you can do about this...

Hydranth answered 5/1, 2011 at 20:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.